【问题标题】:Is there a way to unbind a delegated event on each element instance?有没有办法在每个元素实例上取消绑定委托事件?
【发布时间】:2013-02-12 22:09:14
【问题描述】:

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

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

小提琴:http://jsfiddle.net/JcmpN/

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

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)');
});

【问题讨论】:

标签: jquery jquery-on jquery-delegate


【解决方案1】:

只需让元素不再匹配选择器:http://jsfiddle.net/JcmpN/3/

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

【讨论】:

  • 在监听器中最好使用 .one() 或 $this.off(e)。
【解决方案2】:

将 ID 放在各个跨度上,然后在您的处理程序中添加:

rowref=$(this).attr("id");
$('#'+rowref).click(function(){event.stopImmediatePropagation()}

保持委托处理程序不变,但在事件到达之前拦截事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 2016-11-03
    • 2011-07-31
    相关资源
    最近更新 更多