27

1.我有一个onclick事件,

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

2.单击关闭按钮后

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

3.如果我再次点击#train

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

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

请建议。在此先感谢。

4

2 回答 2

43

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
}

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

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

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

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

NOTE :

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);

Hope this helps!

于 2013-06-22T11:42:00.070 回答
7

绑定和解绑处理程序

关键是范围。

您必须声明和定义function (trainClick(){stuff it does})事件处理程序的外部,以便其他按钮的功能可以看到它。

下面是一个例子。

function trainClick()
{
    alert("train is clicked"); //Notice this function is declared outside event handlers below
}
$('#button1').on("click", trainClick); //this calls the above function

$("#button2").on("click",function(){
    $("#button1").off("click",trainClick); //unbinds button1 from trainClick() function (event handler)
});//End Button 2 click

$("#button3").on("click",function(){
    $("#button1").on("click",trainClick); //binds button1 to trainClick() function (event handler)
});//End Button 2 click
于 2015-11-05T20:12:11.667 回答