Is there a way to unbind a delegated event on each element instance?

天大地大妈咪最大 提交于 2019-12-10 23:42:39

问题


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

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

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

回答1:


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



回答2:


Put IDs on the individual spans, then in your handler add:

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

Leaving the delegated handler intact, but intercepting the event before it gets there.



来源:https://stackoverflow.com/questions/14842762/is-there-a-way-to-unbind-a-delegated-event-on-each-element-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!