首先取消绑定单击,然后绑定(jquery) [英] first unbind click and then bind (jquery)

查看:140
本文介绍了首先取消绑定单击,然后绑定(jquery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1.我有一个onclick事件,

1.I have a onclick event on,

$('#locations').click(function(){
$('#train').unbind('click'); 
//do some stuff
}

2.单击关闭按钮

$('.close').click(function(){
//do some stuff
}

3.再单击一次#train

3.Then again if I click #train

$('#train').bind('click', function() {
alert('train is clicked');
//do some stuff
}

现在的问题是#train没有触发.是否将事件再次绑定到.close函数上?

Now the problem is #train is not firing.Is it to bind the event again on .close function?

请提出建议.谢谢.

推荐答案

看着您的问题,您似乎没有在unbind之后绑定click,因此它不会触发. (假设您按顺序保留了正确的功能).您必须这样做:

Looking at your question, you do not seem to bind back the click after you unbind it, so it will not fire. (Assuming you've kept the sequence of your functionality right). You'll have to do it this way:

//Set a function with the action you need to do after you click the train
function  trainClick() {
  alert('train is clicked');
  //do some stuff
}

解除绑定时,使用函数名称调用unbind:

When you're unbinding, call unbind with the function name:

$('#locations').click(function(){
 $('#train').unbind('click',trainClick);
//do some stuff
}

然后,要绑定点击(点击#close时),您可以使用:

Then, to bind the click (when #close is clicked), you'd use :

$('.close').click(function(){
  $('#train').bind('click',trainClick);
  //do some stuff
}

注意:

一个更好的方法是使用onoff,如果您使用的版本大于jQuery v1.7,因为..那么它将无法正常工作.在上面的代码中,只需将bind替换为on,将unbind替换为off.

A better way would be use on and off, if you are using a version greater than jQuery v1.7 because, well.. then it will not work. In the code above, just replace bind with on and unbind with off.

$('#train').on('click',trainClick);
$('#train').off('click',trainClick);

希望这会有所帮助!

这篇关于首先取消绑定单击,然后绑定(jquery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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