2

私がする必要があるのは、jQuery.one委任を使用して、一致した各要素の機能を取得することです。

ご覧のとおり、「Baz」または「Bat」のリンクをクリックすると、「(削除済み)」が複数回追加されます。一方、「Foo」のリンクをクリックすると、コードが1回だけ実行されますが、「Bar」のコードも無効になります(またはその逆)。

フィドル: http: //jsfiddle.net/JcmpN/

私がしたいのは、これらのいずれかをクリックすると、その要素のハンドラーが実行されますが、他の要素も1回クリックされるまでそのまま残されます。

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

2 に答える 2

1

要素がセレクターと一致しなくなるようにするだけです:http://jsfiddle.net/JcmpN/3/

$('#product-list').on('click.productRemoveOn', 'a.removeWithOn:not(.ignore)', function (e) {
  var $this = $(this).addClass("ignore"),
  ...
于 2013-02-12T22:17:47.377 に答える
0

個々のスパンにIDを配置してから、ハンドラーに次を追加します。

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

委任されたハンドラーはそのまま残しますが、イベントが発生する前にイベントをインターセプトします。

于 2017-10-10T10:29:13.943 に答える