how to rebind click event to anchor after unbind?
I want to unbind the anchor after the first click, but when user click a specific button, I want to rebind the click event to this anchor
I wrote this code
$(document).ready(function(){
$("a.package").click(function(){
//alert('click');
$(this).unbind('click');
// the rest of the code
});
$('#activate').click(function(){
$('a.package').bind('click');
// the rest of the code
});
});
the unbind function works well, but the bind function does not work, wh开发者_开发问答y? and how to make it work?
Store your click function in a variable so that it can easily be re-assigned...
$(document).ready(function() {
var onclick = function(e) {
//alert('click');
$(this).unbind('click');
// the rest of the code
}
$("a.package").click(onclick);
$('#activate').click(function() {
$('a.package').click(onclick);
// the rest of the code
});
});
You have to pass a callback to bind, it doesn't remember anything once it is unbound. Meaning when you specified the bind again in the #activate.click you would have to specify the function there. Probably the best way to do this is specifiy the function else where and use that for the bind call. In the example below i use jquerys .data to store a function under 'clickFunc' and then use this as the callback for the .click . You could just also use a var.
$(document).ready(function(){
$("#package").data('clickFunc', function () {
alert("Click");
$(this).unbind('click');
})
console.log($('#package').oclick);
$("#package").click($('#package').data('clickFunc'));
$('#activate').click(function(){
$("#package").click($('#package').data('clickFunc'));
// the rest of the code
});
});
http://jsfiddle.net/nj65w/13/
Try changing the first binding to .one().
$("a.package").one("click", function(){
// alert('click');
// $(this).unbind('click'); <-- no need, using .one
// call your "when clicked" function
});
$('#activate').click(function(){
$('a.package').click(<your "when clicked" function>);
});
精彩评论