简体   繁体   中英

jquery unbind click doesn't work

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.

如果要使用.unbind(),则需要使用.bind()绑定单击处理程序。

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM