jQuery如何绑定onclick事件以动态添加HTML元素 [英] jQuery how to bind onclick event to dynamically added HTML element
问题描述
我想将onclick事件绑定到我使用jQuery动态插入的元素
I want to bind an onclick event to an element I insert dynamically with jQuery
但它从不运行绑定函数。如果你能指出为什么这个例子不起作用以及如何让它正常运行,我会很高兴:
But It never runs the binded function. I'd be happy if you can point out why this example is not working and how I can get it to run properly:
<!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在评论中指出这一点)
I edited the example to contain two elements the method is inserted to. In that case, the alert()
call is never executed. (thanks to @Daff for pointing that out in a comment)
推荐答案
第一个问题是当你在jQuery上调用append时设置了多个元素,为每个元素创建了要追加的元素的克隆,因此附加的事件观察者将丢失。
The first problem is that when you call append on a jQuery set with more than one element, a clone of the element to append is created for each and thus the attached event observer is lost.
另一种方法是为每个元素创建链接:
An alternative way to do it would be to create the link for each element:
function handler() { alert('hello'); }
$('.add_to_this').append(function() {
return $('<a>Click here</a>').click(handler);
})
另一个潜在的问题可能是在将元素添加到DOM之前附加事件观察者。我不确定这是否有什么要说的,但我认为这种行为可能被认为是不确定的。
一个更可靠的方法可能是:
Another potential problem might be that the event observer is attached before the element has been added to the DOM. I'm not sure if this has anything to say, but I think the behavior might be considered undetermined. A more solid approach would probably be:
function handler() { alert('hello'); }
$('.add_to_this').each(function() {
var link = $('<a>Click here</a>');
$(this).append(link);
link.click(handler);
});
这篇关于jQuery如何绑定onclick事件以动态添加HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!