如何在jQuery中Deattach事件并附加新事件 [英] How to Deattach event and attach new one in jQuery

查看:182
本文介绍了如何在jQuery中Deattach事件并附加新事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在彩盒弹出窗口内的按钮上遇到jQuery点击事件的问题。

Im having problems with jQuery click event on a button inside a colorbox popup.

按钮如下:

<div id="popup">
    <button class="close_bu">Close</button>
</div>

默认情况下附加以下事件:

Which by default have the following event attached:

jQuery('.close_bu').bind('click',function(){        
            jQuery.colorbox.close();
});

当我触发另一个事件时,我想更改默认行为,所以我执行以下操作:

When i fire another event i want to change the default behavior so i do the following:

jQuery('#anotherpopup').on('click','.deleteplan_button',function(){

            jQuery('#popup .close_bu').addClass('returnBack');
            jQuery('#popup .returnBack').removeClass('close_bu');

            jQuery.colorbox({inline:true , href:"#popup", opacity: 0.6, width: "600px"});
return false;
         })

我添加了:

jQuery('#popup').on('click','.returnBack',function(){
                e.preventDefault();
                //Do something
})

但附加到.returnBack的新事件无效,当我点击按钮触发关闭事件时,无关紧要该按钮不再具有.close_bu类,它会继续触发该事件。

But the new event attached to .returnBack is not working and when i click the button is firing the close event , it doesnt matter that the button dont have the .close_bu class anymore, it keep firing that event.

我有点困惑:S

推荐答案

在你的代码中没有id popup 的元素。所以 jQuery('#popup')什么都不做(或者你没有向我们展示代码的重要部分)。

In your code there is no element with the id popup. So jQuery('#popup') will do nothing (or you haven't shown us vital parts of the code).

更新:

您需要使用。unbind()而不是删除类

you will need to use .unbind() instead of removing the class

$('#popup .close_bu').unbind('click');

'#popup .close_bu'你只需选择要与事件连接的元素,或者在这种情况下从事件中取消连接。 jQuery css选择器看起来像css。事件和处理程序之间的连接不使用css。
添加和删除类的全部技巧是触发不同的css样式,它只会改变元素的外观,但不会改变事件。

by '#popup .close_bu' you just select the element you want to wire up with the event, or in this case unwire from the event. The jQuery css selector just looks like css. The connection between the event and the handler doe not use css. The whole trick of adding and removing classes is to trigger different css styles, it will only alter the appearance of an elment, but it won't change events.

这篇关于如何在jQuery中Deattach事件并附加新事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆