<!doctype html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#main_body').append("<h1>Hello</h1><input id=\"but\" type=\"button\">Click");
$("#but").on("click", function() {
alert("bla bla");
});
});
</script>
</head>
<body id="main_body"></body>
</html>
为什么追加 DOM 后警报不起作用?点击后应该显示“bla bla”。
已解决
主要问题是:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
我认为 jquery 太旧了
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
问题已解决:)
最佳答案
对于动态添加的元素,您需要事件委托(delegate),请使用 jQuery 上的其他版本 on() ,您可以将事件委托(delegate)给动态添加元素的静态父级。在您的情况下,您可以使用 #main_body
$('#main_body').on( "click", "#but", function() {
alert( "bla bla" );
});
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery Docs
您的代码有效 here这是因为您在绑定(bind)事件之前添加动态元素,但使用事件委托(delegate)将使您摆脱用于添加动态元素的顺序。
关于javascript - 追加元素后刷新 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22373630/