取消绑定委托事件,其中 jQuery 对象存储在变量中

Unbind delegated event where the jQuery object is stored inside a variable

本文关键字:存储 对象 变量 jQuery 其中 绑定 事件 取消      更新时间:2023-09-26

我正在尝试取消绑定特定元素上的委托事件。现在,我正在找到带有jQuery函数的元素并将其存储在变量中。

但由于它位于变量中并且是委托事件,因此我不确定如何解绑其事件。

在此示例中,当我单击其中一个 Foo 时,其同级 (Bar( 事件应取消绑定:

.HTML:

<div>
    <p class="foo">Foo 1</p>
    <p class="bar">Bar 1</p>
</div>
<div>
    <p class="foo">Foo 2</p>
    <p class="bar">Bar 2</p>
</div>

.JS

$(document).on('click', '.bar', function() {
    alert('Bar');
});
$(document).on('click', '.foo', function() {
    alert('Foo');
    var $sibling = $(this).siblings('.bar');
    // unbind $sibling
});

我试过:

$sibling.off();
$sibling.unbind();
$(document).off('click', $sibling);
$(document).unbind('click', $sibling);

这些都不起作用。

这是小提琴 http://jsfiddle.net/pyL2sLfx/1/

$(document).on('click', '.bar', function() {

这不会在每个".bar"元素上动态绑定事件侦听器。这会绑定文档上的事件侦听器,例如,当发生单击时,当事件冒到文档时,如果事件目标与'.bar'匹配,则调用侦听器。

两种解决方法

  • 带类:

    $(document).on('click', '.bar', function() {
        if( $(this).hasClass('disabled') ) return;
        alert('Bar');
    });
    $(document).on('click', '.foo', function() {
        alert('Foo');
        var $sibling = $(this).siblings('.bar');
        // unbind $sibling
        $sibling.addClass('disabled');
    });
    
  • 使用 stopPropagation:

    $(document).on('click', '.bar', function() {
        alert('Bar');
    });
    $(document).on('click', '.foo', function() {
        alert('Foo');
        var $sibling = $(this).siblings('.bar');
        // unbind $sibling
        $sibling.on('click', function(event) {
            event.stopPropagation();
        });
    });
    

文档:event.stopPropagation()

这是第二种解决方法的变体,例如您可以根据需要调用$sibling.off('click', stopPropagation);

您将事件绑定到文档上,而不是在 p 元素上。但是您正在尝试解绑 p 元素。

将原始绑定更改为此绑定。

$(function () {
    $('.bar').on('click', function() {
        alert('Bar');
    });
    $('.foo').on('click', function() {
        alert('Foo');
        var $sibling = $(this).siblings('.bar');
        $sibling.unbind();
    });
});