0

このコードを使用して、opt1/opt2 を含むドロップダウン リストを変更すると、ID が「ドロップ」であることを示すアラートが表示されます。

「clickme」テスト エントリ ボックスをクリックすると、これが新しいドロップダウンに変わりますが、そのオプションを変更しても、ID を通知するアラートは発行されません。

<script language="javascript">
    $(document).ready(function() {
        $('#test').bind('click', function() {
            $(this).replaceWith('<select id="test" name="test"><option value="volvo">Volvo</option><option value="saab">Saab</option><option value="mercedes">Mercedes</option><option value="audi">Audi</option></select>');
        });

        $("select").change(function(event) {
            alert(this.id);
        });
    });
</script>

<form>
    <input id='test' name='test' type='text' value='ClickMe.'><br>
    <select id='drop' name='drop'>
        <option value='0'></option>
        <option value='1'>Opt1</option>
        <option value='2'>Opt2</option>
    </select><br>

    <input type='submit' value='submit'><br>

    <?php
        if (isset($_REQUEST['test'])) echo $_REQUEST['test'];
    ?>

id新しいドロップダウン リストの が表示されないのはなぜですか?

ありがとう

4

4 に答える 4

2

イベント委任

$(document).ready(function () {

    $('#test').bind('click', function () {
        $(this).replaceWith('<select id="test" name="test"><option value="volvo">Volvo</option><option value="saab">Saab</option><option value="mercedes">Mercedes</option><option value="audi">Audi</option></select>');
    });

    $('form').on('change', 'select[name="test"]', function (event) {
        alert(this.id);
    });

});

デモ:フィドル

通常のイベント登録モデルを使用すると、ハンドラー登録の実行時点で dom に存在する対象に直接ハンドラーが登録されます。したがって、後で動的に追加される要素は、これらのハンドラーを取得しません。

The solution to this is to use event delegation, in this model the handler is registered to a ancestor element which will be present when the page is loaded with the a selector to filter out the source element. This makes use of event propagation - events happening in an element is propagated to all the ancestor elements(there are few exceptions like focus event). So an event happening in an element gets propagated to the ancestor element in one of them the handler is registered then the events source element(event.target) and its ancestors is matched against the selector passed as the second parameter, if it is satisfied then the handler is executed.

于 2013-09-04T09:35:09.287 に答える
0

使ってください

$(document).on('change', 'select', function(event) {
    alert(this.id);
});

jQuery1.6以下を使用している場合は、.liveを使用してください

$("select").live('change', function(event) {
    alert(this.id);
});
于 2013-09-04T09:42:07.170 に答える