有没有办法解除每个元素实例上的委托事件的绑定? [英] Is there a way to unbind a delegated event on each element instance?

查看:100
本文介绍了有没有办法解除每个元素实例上的委托事件的绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做的是使用委托在每个匹配的元素上获得 jQuery.one 的功能。

What I need to do is get the functionality of jQuery.one on each matched element using delegation.

正如您所看到的,单击Baz或Bat的链接会多次附加(已删除)。另一方面,单击Foo的链接只执行一次代码,但也禁用Bar(反之亦然)。

As you can see clicking on the link for "Baz" or "Bat" appends "(removed)" multiple times. On the other hand clicking the link for "Foo" executes the code only once, but then also disables it for "Bar" (or vice versa).

小提琴:< a href =http://jsfiddle.net/JcmpN/ =nofollow> http://jsfiddle.net/JcmpN/

我想要发生的是点击其中任何一个执行该元素的处理程序,但保持其他元素完整,直到它们也被点击一次。

What i want to happen is that clicking on any of these executes the handler for that element, but leaves the others intact until they are also clicked once.

HTML:

<ul id="product-list">
  <li>
    <span class="product-name">Foo</span>
    <a href="#remove-foo" class="removeWithOne">Remove Product</a>
  </li>
  <li>
    <span class="product-name">Bar</span>
    <a href="#remove-bar" class="removeWithOne">Remove Product</a>
  </li>
  <li>
    <span class="product-name">Baz</span>
    <a href="#remove-baz" class="removeWithOn">Remove Product</a>
  </li>
  <li>
    <span class="product-name">Bat</span>
    <a href="#remove-bat" class="removeWithOn">Remove Product</a>
  </li>
</ul>

jQuery:

// this version removes the handler as soon as any instance is clicked!
$('#product-list').one('click.productRemoveOne', 'a.removeWithOne', function (e) {
  var $this = $(this),
      $name = $this.siblings('span.product-name');

  e.preventDefault();

  $name.text($name.text() + ' (removed)');
});

// this one executes the handler multiple times!
$('#product-list').on('click.productRemoveOn', 'a.removeWithOn', function (e) {
  var $this = $(this),
      $name = $this.siblings('span.product-name');

  e.preventDefault();

  $name.text($name.text() + ' (removed)');
});


推荐答案

只需使元素不再与选择器匹配:< a href =http://jsfiddle.net/JcmpN/3/ =nofollow> http://jsfiddle.net/JcmpN/3/

Simply make the element no longer match the selector: http://jsfiddle.net/JcmpN/3/

$('#product-list').on('click.productRemoveOn', 'a.removeWithOn:not(.ignore)', function (e) {
  var $this = $(this).addClass("ignore"),
  ...

这篇关于有没有办法解除每个元素实例上的委托事件的绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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