1. Problem description
After dynamically adding a piece of html code with jQuery's append() method, it is found that the new element cannot be obtained when the click event is bound to the newly added element.
Two, the solution
Elements are added using jQuery's on() method.
Three: key code
$().ready(
function
(){
$(
"#click1"
).bind(
"click"
,
function
(){
$(
"p"
).append(
"<div class='new'><b>I'm clicked!</b></div>"
);
});
//on方法要先找到原选择器(p),再找到动态添加的选择器(.new)
$(
"p"
).on(
"click"
,
".new"
,
function
(){
$(
this
).remove();
});
});
Original blog: https://www.jb51.net/article/87287.htm ;