I have a strange problem with JQuery when I try to click on append element that is inside timeout function I got the following code:
function generate(){
box = shuffle(box);
console.log(box);
$("#game").empty();
for (var i = 0; i < 4; i++) {
$("#game").append("<div class=box>" + box[i] + "</div>");
}
}
function lvl1(){
box = shuffle(box);
console.log(box);
$("#game").empty();
for (var i = 0; i < 4; i++) {
$("#game").append("<div class=box>" + box[i] + "</div>");
}
}
generate();
setTimeout(function(){
lvl1();
}, 1000);
$(".box").click(function(){
alert("OK");
});
If I try to click on box within a 1 sec the alert is showed correctly but if I try to click after the timeout it does nothing also no error is showing
The .box
elements are being appended dynamically, so you need to use a delegated event:
$("#game").on('click', '.box', function () {
alert("OK");
});
This looks like an event delegation issue. On the new boxes created during lvl1 you arnt assigning the event handler again.
Try
$( "#game" ).on( "click", ".box", function(){
alert("OK");
});
see the code:-
$(document).on("click",".box",function(){
alert("OK");
});
working example:- http://jsfiddle.net/f4kgvaL5/2/
thanks
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.