2

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.

1
  • Do this: $("div.init_box").off("click"); Hope it helps :) API api.jquery.com/off Commented Oct 22, 2013 at 2:09

3 Answers 3

2

You need to bind the click handler using .bind() if you are going to use .unbind();

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.