AFAICT这应该有效,但事实并非如此。使用jQuery 1.9.0,我有以下内容:
<html>
<head>
<script type="text/javascript" src="js/libs/jquery-1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("button").click(function() {
$("#area").html("<p>click me</p>");
});
$("p").on("click", function() {
alert($(this).text());
});
});
</script>
</head>
<body>
<p>some text</p>
<button>Create me</button>
<div id="area"></div>
</body>
</html>
为什么点击“某些文字”会发出警报,但点击生成的“点击我”不是?我认为.on()的重点是在动态生成的代码上启用事件处理程序。根据{{3}},这应该有效,但事实并非如此。见Click event doesn't work on dynamically generated elements
答案 0 :(得分:3)
.on()
不是.live()
的替代品。您需要使用事件委派语法:
$('#area').on('click', 'p', function() {
...
});