<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("h2").html("<p class='test'>click me</p>")
});
$(".test").click(function(){
alert();
});
});
</script>
</head>
<body>
<h2></h2>
<button>generate new element</button>
</body>
</html>
我试图生成一个类名为 test
的新标签在<h2>
通过点击按钮。我还定义了一个与 test
关联的点击事件.但是该事件不起作用。
有人能帮忙吗?
您正在使用的 click()
绑定(bind)称为“直接”绑定(bind),它只会将处理程序附加到已经存在 的元素。它不会绑定(bind)到将来创建的元素。为此,您必须使用 on()
创建一个“委托(delegate)”绑定(bind)。 .
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
Source
这是您要查找的内容:
var counter = 0;
$("button").click(function() {
$("h2").append("<p class='test'>click me " + (++counter) + "</p>")
});
// With on():
$("h2").on("click", "p.test", function(){
alert($(this).text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<h2></h2>
<button>generate new element</button>
以上内容适用于使用 jQuery 1.7+ 版本的用户。如果您使用的是旧版本,请参阅下面的先前答案。
上一个答案:
尝试使用 live()
:
$("button").click(function(){
$("h2").html("<p class='test'>click me</p>")
});
$(".test").live('click', function(){
alert('you clicked me!');
});
为我工作。 Tried it使用 jsFiddle。
或者有一种新方法可以用 delegate()
来实现:
$("h2").delegate("p", "click", function(){
alert('you clicked me again!');
});
An updated jsFiddle .