Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
396 views
in Technique[技术] by (71.8m points)

onclick - first unbind click and then bind (jquery)

1.I have a onclick event on,

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

2.Once the close button is clicked

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

3.Then again if I click #train

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

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

Please suggest.Thanks in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...