3

I have read some post about why do not use jQuery.live() and I want to check if I got it:) When I call $("body").delegate('element','click', function);

Is it the same as $(element).live('click', function) ? In case of normal behaviour..According to the post there are some stopPropagation and performance boons, but is the main difference that live bind everytime to body element, while delegate can bind to another one?

4

5 に答える 5

6

重要な違いの 1 つは、「.live()」関数自体はセレクター文字列しか必要としないにもかかわらず、「.live()」は実際には初期セレクターの jQuery 要素リストを作成することです。つまり、セレクターが多少高価な場合、ハンドラーを設定するコードが正当な理由もなく DOM 全体で実行されることになります。「.delegate()」呼び出しはそれを行いませ

本当に、新しいコードで「.live()」を使用する理由がわかりません。これは一種のアーキテクチャ上のミスであり、最終的には静かに消滅するはずです。

于 2011-04-07T21:59:41.923 に答える
5

Nettutsには、これを説明するためのスクリーンキャストがあります:クイック ヒント: Live() と Delegate() の違い

サイトからの引用:

// Live(), introduced in 1.3, allows for the binding  
// of event handlers to all elements that match a  
// selector, including those created in the future.  
// It does this by attaching the handler to the document.  
// Unfortunately, it does not work well with chaining.  
// Don't expect to chain live() after calls like  
// children().next()...etc.  
$("li").live("click", function() {  
    $(this).parent().append("<li>New Element</li>");  
});   

// Delegate, new to version 1.4, perhaps should have been a complete  
// replacement for Live(). However, that obviously  
// would have broken a lot of code! Nonetheless,  
// delegate remedies many of the short-comings  
// found in live(). It attaches the event handler  
// directly to the context, rather than the document.  
// It also doesn't suffer from the chaining issues  
// that live does. There are many performance benefits  
// to using this method over live().  
$('#items').delegate('li', 'click', function() {  
    $(this).parent().append('<li>New Element</li>');  
});   
于 2011-04-07T21:59:06.907 に答える
4

デリゲートは別のものにバインドできますが、毎回ボディ要素にライブバインドする主な違いは何ですか?

はい、正確に。行を追加および削除するテーブルがあり、それらの行 (または行内のリンクまたはボタン) のクリックを処理したいとします。それを使用することもできliveますが、イベントは本体レベルまでバブルする必要があり、それに直面してみましょう。それはグローバル変数のように感じます。delegate代わりにon要素を使用するtableと、より的を絞ったままになり、ページで行われている他のことから分離されます。delegateは、よりモジュール化された、 の含まれたバージョンですlive

于 2011-04-07T22:01:13.877 に答える
3

要するに.live、ドキュメント レベルで.delegate実行され、指定した要素で実行されます。なぜ違いが生じるのですか?を使用してバインドされた mousemove イベント (または複数) がある場合.live、jQuery は、マウスをページ上の任意の場所に移動するたびにコードを実行して、コールバック関数を実行する必要があるかどうかを確認します。これは非常に非効率的であり、.delegate. .delegate関数は、指定した dom ノード内でイベントが発生した場合にのみ実行されます。たとえば、あなたが言った場合$('ul#myUL').delegate(...)、jQuery は、イベントが内部から発生したときにコードを実行する必要があるかどうかのみを確認します。ul#myUL

于 2011-04-07T22:03:56.173 に答える
3

.live() メソッドは、ドキュメントの先頭に伝播したイベントを処理するため、ライブ イベントの伝播を停止することはできません。同様に、.delegate() によって処理されるイベントは、常に委譲先の要素に伝達されます。その下の要素のイベント ハンドラーは、委任されたイベント ハンドラーが呼び出されるまでに既に実行されています。

于 2011-04-07T21:59:41.783 に答える