有什么办法在jQuery中委托事件一个? [英] Is there any way to delegate the event one in jQuery?

查看:141
本文介绍了有什么办法在jQuery中委托事件一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想委派活动一个 点击。是否有人知道是否可以做到?

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()处理程序的固有问题w /委托是使用.one()在选择器中匹配的每个元素绑定其自己的事件处理程序。因此,当它第一次被触发时,它解除绑定/从该元素中删除处理程序。你不能用.delegate()做,因为只有一个SINGLE处理程序被用于所有匹配的元素。

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).

这篇关于有什么办法在jQuery中委托事件一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆