我遇到了这个问题(在此总结),其中Jquery .on方法将侦听器添加到加载页面时创建的第一个按钮,但是当通过单击上一个按钮创建另一个按钮时,新按钮不包含任何内容侦听器,尽管我指出它应该在内部查找具有id且具有变量count值的元素。根据.on方法,您可以将侦听器添加到页面稍后创建的对象中。
这是HTML:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<script src="script.js"></script>
</body>
</head>
这是script.js
var count = 1;
$("body").html("<button id=\"" + count +"\">1</button>");
$("body #" + count).on("click", function(){
count++;
$("body").html($("body").html() + "<button id=\"" + count +"\">" + count +"</button>");
});
var count = 1;
$("body").html("<button id=\"" + count +"\">1</button>");
$("body").on('click', '#' + count, function() {
count++;
$("body").html($("body").html() + "<button id=\"" + count +"\">" + count +"</button>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
使用.on()
您可以一次定义函数,它将对任何动态添加的元素执行。
例如
$(document.body).on('click', 'body #' + count, function() {
//do something
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句