jQuery: live() - 只能活一次吗?

3
我在跟进这个线程,以禁用/启用按钮的单击事件为例, 最佳方法是使用jQuery删除事件处理程序?

其想法是您还可以使用live()方法来启用/禁用事件。 此代码的作用是,当您单击a标签元素(例如.load-item)时,它将向此元素添加disabled类。 这将使选择器不再匹配该元素,并且事件将不会触发,直到“已禁用”类被删除,使.live()选择器再次有效。

下面是我编写的代码,它确实禁用了第一个按钮的单击事件:

$('.load-item:not(.disabled)').live('click',function(){


/* add a .current class to the target item */
$(this).parentsUntil('.column-global').addClass('current');

/* add .disabled class to each a tag in the .current element-div */
$('.current a').each(function(index) {
    $(this).addClass('disabled');
});

....

});

我还有另一个功能,当您单击另一个按钮时,可以删除禁用类(disabled-class)。

$('.button-return').click(function(){

    ...

    /* remove all the .disabled class if any exists */
    $('.current a').each(function(index) {
        $(this).removeClass('disabled');
    });

    ...

    /* remove all the .current class if any exists */
    $('.item-global').removeClass('current');



    return false;

});

我已经检查过了,它确实移除了disabled-class,但第一个按钮仍然没有回到原始的可点击状态。 我有遗漏什么吗?或者live()只能使用一次?如果live()不是我应该使用的方法,是否有更好的解决方案? 谢谢。
2个回答

1
你的返回按钮也需要是一个实时事件
$('.button-return:not(disabled)').live("click",function(){...});

同时,在使用addClass()和removeClass()时,您不需要在选择器上使用each。只需调用它即可。

$('.current a').each(function(index) {
    $(this).removeClass('disabled');
});

与此相同

$('.current a').removeClass('disabled');

编辑过的

当您将实时事件添加到返回按钮时,请注意需要验证其未被禁用。

它在这里完美运行,这是一个简单的 demo. http://www.jsfiddle.net/Qax3n/


为什么.button-return需要是live的?我没有看到这个类在任何地方被动态操作... - Nick Craver
尝试了一下,在.button-return上添加了live()但仍无效。感谢有关removeClass()的提示。 - Run
我找到了我的问题所在 - 在使用load()之后,我有这行代码:$('.disabled').click(function(){return false;}); 如果我不使用这行代码,页面会“返回true” - 跳转到另一个页面,并带着a标签按钮的链接 - <a href="">button 1</a>... 你有什么解决办法吗? - Run
这是完整的jQuery代码,如果您不知道我上面所说的,请访问http://www.jsfiddle.net/9v4Yd/1/ :-) - Run
尝试使用click(function(event){event.preventDefault();});函数。 - methodin
显示剩余3条评论

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接