gpt4 book ai didi

javascript - jQuery .click() 在不存在的 html 元素上触发事件

转载 作者:太空宇宙 更新时间:2023-11-04 14:13:50 25 4
gpt4 key购买 nike

我有一个 ID 为“打开”的 HTML 按钮。我添加了一个 jQuery .click() 绑定(bind)到由 ID 选择的 HTML 按钮。在 .click() 绑定(bind)中,我将“打开”的 ID 更改为“关闭”。但是,即使 ID 已更改为“关闭”,随后对“打开”按钮的点击仍会触发。代码如下:

index.html

<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id="open">Open</button>

<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>

索引.js

$('#open').click(function() {
console.log("clicked");
$(this).attr('id', 'close');
});

https://jsfiddle.net/iHexBot/28tj1ywg/

我期待/希望看到控制台日志只被“点击”一次。但是,即使 HTML 元素 ID 不再“打开”,每次单击按钮时它都会记录“已单击”。有人可以向我解释为什么会发生这种情况,如果可能的话,如何解决这个问题?

最佳答案

您可以将事件绑定(bind)到文档而不是像这样的元素

$(document).on('click', '#open', function() {
console.log('this will only be displayed as long as id is "open"');
});

关于javascript - jQuery .click() 在不存在的 html 元素上触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33480600/

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