为什么我无法获得这个新添加的多个子div的text
。我使用JQuery添加这些动态元素。这里是我的样本小提琴:JSFIDDLE
有人可以向我解释我哪里出错了吗?
脚本
var counter = 0;
$("button").click(function() {
$("<div class='child-list-workorder'>\
<div class='list-workorder'>\
<div class='list-workorder-header'>\
<h3 id='" + counter + "' class='list-workorder-id'>click me " + (++counter) + "</h3>\
</div>\
<p>" + counter + "</p>\
</div>\
</div>").appendTo("div.parent-list-workorder");
});
$("div.list-workorder-header").on("click", "h3.list-workorder-id", function(){
alert(this.id);
});
答案 0 :(得分:1)
你必须使用delegated event,因为html是动态生成的:
$(document).on("click", "h3.list-workorder-id", function(){
alert(this.id);
});
您的div
$(".child-list-workorder").on("click", "h3.list-workorder-id", function(){
...............
不起作用,因为它也是动态生成的。
或者您可以使用在DOM加载时加载了类 parent-list-workorder 的父div:
$(".parent-list-workorder").on("click", "h3.list-workorder-id", function(){
alert(this.id);
});