作者tomin (藍藍紫黃橘 粉灰白綠咖)
看板Ajax
標題Re: [問題] 事件綁定在父節點
時間Tue Nov 23 14:46:22 2010
※ 引述《mesak (米沙)》之銘言:
: $('#parent_p').bind('click',function(evt){
: var o=evt.target;
: alert( $(o).attr('id') )
: })
: $('#parent_p a', $('#parent_p') ).bind('click',function(){
^^^^^^^^^^^改成a
: alert( $(this).attr('id') )
: })
: 兩者是不是 效能差不多??
我測的結果 前者比較快
console.time('profile 6');
for ( var i=0; i < 10000; i++) {
$('a',$('#primary')[0]).click(function(){});
}
console.timeEnd('profile 6');
console.time('profile 7');
for ( var i=0; i < 10000; i++) {
$('a','#primary').click(function(){});
}
console.timeEnd('profile 7');
console.time('profile 8');
for ( var i=0; i < 10000; i++) {
$('#primary').click(function(event){var o=event.target});
}
console.timeEnd('profile 8');
6,7,8分別是2121ms, 1003ms, 266ms
不同DOM、不同jQuery版本可能會測出不同結果 我的結果就跟別人的不太一樣
http://brandonaaron.net/blog/2009/06/24/understanding-the-context-in-jquery
我測到的其他結果(in jQuery 1.4.3)有
1.一般情況(綁定事件不多時)下 delegate比live快
需大量綁定時,live比較快
2. $('#primary a'); //173ms
>> $('a','#primary'); //216ms
>= $('#primary').find('a'); //228ms
後兩者其實差不多,互有高低。
我比較驚訝的是第一種selector永遠是最快的。
雖然我喜歡這樣的結果,但不太有把握這是正確答案。
而且selector對速度的影響滿大的,selector後面接什麼method倒是其次。
3.context有時會表現不佳 worst case會特別慢
到底該怎麼有效的「重覆」利用它哩?
比如在外部宣告context,共用同一個context
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.122.30.198
※ 編輯: tomin 來自: 140.122.30.198 (11/23 14:57)
推 mesak:感謝 測試與解答 !! 11/23 18:18
→ TonyQ:第一個會最快是可能是因為抄 qSA的捷徑。 11/23 18:41