有没有办法在 jQuery 中委托事件之一?
我想委托活动click 的 .com/one/" rel="nofollow">one.有谁知道是否可以这样做?
I would like to delegate the event one for the click. Does anyone know if it is possible to do it?
推荐答案
我将假设您希望事件只触发一次 PER 匹配的元素,而不是在第一次点击时完全解除绑定.
I'm going to assume that you want the event to fire only once PER matched element rather than unbind entirely on the first click.
我会这样实现它:
$('#container').delegate('.children', 'click', function() {
if($(this).data('clicked')) {
return;
}
// ... your code here ...
$(this).data('clicked', true);
});
每个元素只会触发一次.从技术上讲,它每次都会触发,但在第一次单击时会被标记,因此代码不会再次执行.
This will fire only once per element. Technically, it fires everytime but is flagged the first time it is clicked so the code will not execute again.
使用委托模拟 .one() 处理程序的固有问题是使用 .one() 选择器中匹配的每个元素都绑定了自己的事件处理程序.因此,当它第一次被触发时,它会从该元素中取消绑定/删除处理程序.你不能用 .delegate() 做到这一点,因为只有一个处理程序被用于所有匹配的元素.
The inherent problem of simulating a .one() handler w/ delegate is that using .one() each element that was matched in the selector is bound its own event handler. So when it is fired for the first time it unbinds/removes the handler from that element. You can't do that with .delegate() because only a SINGLE handler is being used for ALL the matched elements.
虽然上面的代码完美地模拟了它,但它仍然有些骇人听闻,因为它并没有真正做 .one() 所做的事情(解除绑定事件处理程序).
While the code above simulates it perfectly, it is still somewhat hackish because it doesn't literally do the same thing that .one() does (unbinding an event handler).
相关文章