1

問題のフィドル

$('div').not('#logs').each(function () {
    var id = $(this).attr('id');
    $("#" + id).bind('click', function () {
        $('#logs').append('\n' + $(this).attr('id') + '\n');
    });
});

$(".test").live('click', function () {
    alert('from x');
});

私がしたことは、いくつかのdivを作成し、各関数を使用してすべてのdivをループし、各divのクリックイベントをバインドしたようなものです。

上記のようにライブ機能をバインドしたクラス名「test」の各div内にスパンがあります。スパンをクリックすると、「x から」というアラートのみが表示されるはずですが、動作がわかりません。

動作は、バインド機能も機能しており、ライブ機能も機能しています。

私の文章形成の間違いをお詫び申し上げます。私は問題を説明するのが少し下手です。行動の説明を待っています。

ありがとう

4

2 に答える 2

0

Events are bound to the elements that exist on the page at the time events are attached.

In your case the elements were always present on the page when this happened. So both the ways of binding events would work.

The 2nd case is event delegation which is used to bind events to dynamically created events, i.e elements which are attached to the DOM after the events are bound. So when you use live to bind the event , the event is attached to the document which is always present. Which uses the concept of event bubbling

Maybe elements inserted to the dom after an Ajax request

Code

You don't need the $.each loop as the selector selects all the elements matched by it

$('div').not('#logs').click( function () {
        $('#logs').append('\n' + this.id + '\n');
});

// live has be deprecated to delegate events as of jQuery 1.7
// use on instead to bind the events for event delegation
$(document).on('click', ".test", function () {
    alert('from x');
});

Check Fiddle

于 2013-07-18T07:39:45.653 に答える
0

イベントは DOM ツリーをバブルアップし、途中で要素にバインドされたハンドラーを起動します。

通常は を呼び出して伝達を停止しますがevent.stopPropagation().live()メソッドはイベントがドキュメントの先頭に伝達されるとイベントを処理するため、親要素のclick()メソッドは既に呼び出されています。

次のように変更することで、コードを期待どおりに動作させることができます。

$(".test").on('click', function (event) {
    alert('from x');
    event.stopPropagation();
});

たとえば、これらを動的に作成する場合に本当に使用する必要がある場合は、親要素に使用する.live()代わりに、次のようにも使用します。.bind().live()

$('div').not('#logs').each(function () {
    var id = $(this).attr('id');
    $("#" + id).live('click', function () {
        $('#logs').append('\n' + $(this).attr('id') + '\n');
    });
});

$(".test").live('click', function (event) {
    alert('from x');
    event.stopPropagation();
});

.live()次のように、減価償却の代わりに、より好まれる '.on()' メソッドを使用することもできます。

$('div').not('#logs').each(function () {
    var id = $(this).attr('id');
    $(document).on('click', "#" + id, function () {
        $('#logs').append('\n' + $(this).attr('id') + '\n');
    });
});

$(document).on('click', ".test", function (event) {
    alert('from x');
    event.stopPropagation();
});
于 2013-07-18T07:46:44.067 に答える