如何取消对活动元素上的click事件的绑定,并在单击另一个元素时重新绑定

How to unbind click event on the active element and bind again when another element is clicked?

本文关键字:元素 绑定 单击 新绑定 另一个 click 取消 何取消 活动 事件      更新时间:2023-09-26

我想用一个例子来解释更容易:

HTML:

<div class="boxset">
    <div class="box_header">  
        h1  
    </div>
    <div class="box">
        This is some text for box 1.
    </div>
</div>
<div class="boxset">
    <div class="box_header">  
        h2  
    </div>
    <div class="box">
        This is some text for box 2.
    </div>
</div>
<div class="boxset">
    <div class="box_header">  
        h3  
    </div>
    <div class="box">
        This is some text for box 3.
    </div>
</div>

JS:

$('.box_header').bind("click", function() {
    $('.box').not($(this).next('.box')).animate({
        'width': 'hide'
    });
    $(this).next().animate({
        'width': 'show'
    });
});

jsFiddle:

http://jsfiddle.net/rDHMF/

这是一个简单的横向手风琴菜单。现在,当我单击标题(h1, h2, h3)时,将显示其相应的内容,并且先前打开的内容将关闭。但是,我可以再次点击刚才点击的标题它会收缩并展开。

是否有可能暂时解除我刚刚单击的标题上的单击事件的绑定,以便"活动"标题将在我单击它时保持不变?然后当我点击另一个标题时再次绑定。如果是,怎么做?

应该这样做:

$('.box_header').bind("click", function() {
    $('.box').not($(this).next('.box')).animate({
        'width': 'hide'
    });
    $(this).next().animate({
        'width': 'show'
    });
});

你不需要取消/重新绑定事件,只要防止盒子收缩,当它是相同的

我会用另一种方式来做。每当用户单击头文件时,向头文件添加一个active类(并从其他头文件中删除它)。并做一些其他的事情,如果这个头已经有一个active类(只从这个头和动画中删除一个头)。这种方式还允许我们自定义活动页眉的样式。