gpt4 book ai didi

javascript - Jquery .on Listener 不要给新元素添加点击监听器

转载 作者:行者123 更新时间:2023-11-30 20:39:19 25 4
gpt4 key购买 nike

我遇到了这个问题(我在这里总结),其中 Jquery .on 方法将监听器添加到加载页面时创建的第一个按钮,但是当通过单击前一个按钮创建另一个按钮时,新按钮会执行不包含任何监听器,尽管我指出它应该在 body 内部查找具有变量 count 值的 id 的元素。根据 .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
});

关于javascript - Jquery .on Listener 不要给新元素添加点击监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49465420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com