You need to bind the click handler using .bind() if you are going to use .unbind();
jquery unbind click doesn't work
-
01-07-2022 - |
Вопрос
Please give me a hand.Thanks in advance! Here is the simple coding:
var $newbox = $( "<div/>" );
$newbox.addClass("init_box");
for(i=0; i<3; i++) {
$("#game").append($newbox.clone().click(function(){
$(this).addClass("select_box");
$("div.init_box").unbind("click");
}));
}
I wanna create 3 divs and once any one of this 3 divs is clicked, then others will unbind the click event. But the code above doesn't work.
Решение
Другие советы
I'll use .on() and .off() with namespaced event handler like
var $newbox = $('<div/>', {
'class': 'init_box'
}).on('click.select', function () {
$(this).addClass("select_box");
$("#game .init_box").off("click.select");
});
for (i = 0; i < 3; i++) {
$newbox.clone(true, true).appendTo('#game').html(i)
}
Demo: Fiddle
This should work.
var $newbox = $( "<div/>" );
$newbox.addClass("init_box");
for(i=0; i<3; i++) {
$newbox.clone().appendTo("#game").click(function(){
$(this).addClass("select_box");
$("div.init_box").unbind("click");
});
}
In your example you're attempting to add the handler to the object before it's inserted into the DOM, this doesn't work.
You must first insert it into the DOM, then add the handler.
Alternatively you can use live binds. http://api.jquery.com/on/
Не связан с StackOverflow