gpt4 book ai didi

javascript - 每次加载文档时都会执行 click 函数

转载 作者:行者123 更新时间:2023-11-28 19:16:17 25 4
gpt4 key购买 nike

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>click demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
for(var c=1; c<=5; c++){
var btn = $("<button>Button "+c+"</button>");
btn.click(new function(){
alert("You click button "+c);
});
$("body").append(btn);
}
</script>
</body>
</html>

有人可以向我解释为什么每次加载页面时都会执行 click 函数吗?我希望该按钮在单击时显示警报框,但不幸的是没有任何反应!有什么想法吗?

最佳答案

从按钮点击处理程序中删除new。此外,您需要更新代码以获得单击按钮的正确索引,如下所示。使用将代码包装在闭包中的for内。

for (var c = 1; c <= 5; c++) {
var btn = $("<button>Button " + c + "</button>");
(function (c) {
btn.click(function () {
alert("You click button " + c);
});
}(c));
$("body").append(btn);
}
<小时/>

编辑

更好的方法是使用 event delegation使用 data-* 属性在 HTML 元素中存储信息。

for (var c = 1; c <= 5; c++) {
var btn = $("<button class='myButton' data-title=" + c + ">Button " + c + "</button>");
$("body").append(btn);
}

$(document.body).on('click', '.myButton', function() {
document.write('You clicked ' + $(this).data('title') + ' button');
});

关于javascript - 每次加载文档时都会执行 click 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29744049/

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