单击一个按钮后,会更改 body 标记中的 html,其中有一个新按钮。单击"new"按钮时,应该会发出警报消息,但事实并非如此。
我认为可能是 document.ready 部分,需要重新初始化。但我不知道该怎么做。请检查代码:
<!DOCTYPE html>
<html>
<head>
<title>Title For the Website</title>
<script src="js/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="bigbox">
<button id="idol">Idol</button>
</div>
<script>
$(document).ready(function(e){
$('#idol').click(function(event) {
console.log("success");
var x = '<button id="clickhere">Click Here!</button></div></div>';
$('#bigbox').html(x);
});
$('#clickhere').click(function(event) {
alert('This is working');
});
});
</script>
</body>
</html>
这是我的代码的精简版本。在原始页面中,一个按钮通过 ajax 调用生成一些 html,并且该 html 有一个按钮可以执行另一个 ajax 调用。
最佳答案
使用事件委托(delegate)
如下:
$(document).on('click', '#clickhere', function(event) {
alert('This is working');
});
发生这种情况是因为您的按钮是动态添加的,因此它不在 dom 中。 事件委托(delegate)将确保事件从文档委托(delegate)到按钮。
关于javascript - 简单的 Javascript Jquery 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31291438/