Friday, 21 July 2017

javascript - Why click() does not work for appended elements?

Use on to delegate the click events.



$("body").on("click","td",function(){
alert('clicked');

});


This will take click events from elements whose parent is "body" and whose target is "td" and then use the callback function. This process of delegation inspects each click event and is done at the time of the event.



The click process you show in your question will only assign the event once, at the time of execution. As a result, only the "td" matches at that time will receive the event handler.



Another option you have, since you are creating these elements in script, is to assign the handler to them before they are appended to the page.



$(".addnewrow").click(function(){

var row = $("new");
$("td",row).click(function(){
alert("clicked");
});
$("table").append(row);
});


It depends on what else is happening on the page which approach fits best.

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...