0

jquery関数の使用と使用on後の呼び出しの違いは何ですかfindon

<div class="outer">
    <span>One</span>
    <div class="inner"><button id="button">button 1</button></div>
</div>
<div class="outer">
    <span>Two</span>
    <div class="inner"><button id="button">button 2</button></div>
</div>

jqueryコードは

$(document).ready(function(){

    $('div.outer').on('click',".inner #button",function(event){
        console.log(this);//this works
    });
    $('div.outer').find(".inner #button").on("click",function(event){
        console.log(this);//this works
    });
    $('div.outer').find(".outer span").on('click',function(event){
        console.log(this);//this not works
    });
});

これは、各ボタンが 2 回クリックされるように、複数のインスタンスを持つ jquery プラグインを作成している簡単な例です。jquery.off各関数をバインドする前に使用しましたが、機能しません。

4

3 に答える 3

0

IDは一意である必要があります。

何をしようとしているのかわからないが、HTML構造による

$('div.outer').find(".outer span").length === 0; //true
于 2013-01-29T13:41:18.380 に答える
0

1つ目は動的イベントハンドラーで、イベントをdiv.outerの親であるにバインドします#buttonが、セレクターに基づいてフィルター#button処理します。これにより、イベントのバインド時に要素が存在しなくても、つまり動的に挿入された要素が機能します。

最後の2つは通常のイベントハンドラーであり、find()別の要素内の要素を見つけるだけなので、真ん中の1つでは、#button.innerを検索し.outer、通常のイベントハンドラーをにアタッチし#buttonます。

IDは一意であるため、その方法で検索を使用する$('#button').on()必要はありません。十分なはずです。

最後の1つでは、クリックはボタンではなくスパンにバインドされているため、ボタンをクリックしてもイベントは発生しませんが、スパンをクリックすると発生します。

編集:

.outerセレクターはinsideを検索します。そのため、セレクターは機能し.outerません。.outer内のスパンだけを検索する必要があるため、次のようになります。

$('div.outer').find(".outer span")

これである必要があります:

$('div.outer').find("span")

フィドル

于 2013-01-29T13:41:32.020 に答える
0

on() を使用すると、イベント リスナーを任意の要素にアタッチし、別の要素 (その要素内) によってトリガーできるように指定できます。

この場合、イベント リスナーは ID が「button」の要素になります。

$('#button').on('click', function(){
    console.log('if you dynamically remove #button from the page the event will be lost');
})

この場合、イベント リスナーは要素の本体になります。

$('body').on('click', '#button', function(){
    console.log('if you dynamically remove #button from the page the event will not be lost');
})

さて、find() の使用に関して、私は css セレクターを使用することを好みます。次のようなことを試してください。

$('div.outer span').on('click', function(event){
    console.log('this works');
    console.log(event.currentTarget); //the element you have clicked on
});
于 2013-01-29T13:48:36.573 に答える