gpt4 book ai didi

javascript - jQuery 如何将 onclick 事件绑定(bind)到动态添加的 HTML 元素

转载 作者:IT王子 更新时间:2023-10-29 02:38:48 24 4
gpt4 key购买 nike

<分区>

我想将一个 onclick 事件绑定(bind)到我使用 jQuery 动态插入的元素

但它从不运行绑定(bind)函数。如果您能指出为什么这个示例不起作用以及我如何让它正常运行,我将很高兴:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"        
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="da" lang="da">
<head>
<title>test of click binding</title>

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">


jQuery(function(){
close_link = $('<a class="" href="#">Click here to see an alert</a>');
close_link.bind("click", function(){
alert('hello from binded function call');
//do stuff here...
});

$('.add_to_this').append(close_link);
});
</script>
</head>
<body>
<h1 >Test of click binding</h1>
<p>problem: to bind a click event to an element I append via JQuery.</p>

<div class="add_to_this">
<p>The link is created, then added here below:</p>
</div>

<div class="add_to_this">
<p>Another is added here below:</p>
</div>


</body>
</html>

编辑:我编辑示例以包含方法插入到的两个元素。在这种情况下,永远不会执行 alert() 调用。 (感谢@Daff 在评论中指出这一点)

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