是否使用delegate() [英] To use delegate() or not
问题描述
是否有人可能能够解释为什么使用诸如
Is there someone who might be able to explain why using a function such as
$('#potato').delegate('.frenchFry', 'click', function(e){
// do something...
});
优于
$('#potato').bind('click', function(e){
if($(e.target).hasClass('frenchFry'){
// do something...
}
});
假设一大片在一个非常动态且不断变化的#potato上的代表团数量是否有使用委托的速度优势(不是我可以提出的任何测试)?
assuming a large number of delegations on a very dynamic and constantly changing #potato? is there a speed advantage to using delegate (not from any tests i could come up with)?
推荐答案
因为 e.target
将引用所点击的最深层嵌套元素,这可能没有您正在寻找的类。
Because e.target
will refer to the most deeply nested element clicked, which may not have the class you're looking for.
<div class="frenchFry>
<span>some nested text</span>
</div>
$(e.target).hasClass('frenchFry') // click on the <span> will return "false"
如果你确定实际的 e.target
将永远是你想要的元素,那么这不会是一个问题。
If you're certain that the actual e.target
will always be the element you intend, then this won't be an issue.
使用基于 .delegate()
的选择器测试的不仅仅是 e。目标
本身只是让它变得更有活力。
Having a selector based .delegate()
that tests more than just the e.target
itself simply makes it a little more dynamic.
编辑:顺便说一句,你可以排序复制 .delegate()
这样的事情:
By the way, you could sort of replicate .delegate()
something like this:
var node = e.target;
while( node && !$(node).is('.frenchFry') ) {
node = node.parentNode;
if( node === this || node === document.body ) {
node = null;
break;
}
}
if( node ) {
// do something
}
这篇关于是否使用delegate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!