如何将 click 事件绑定到 jQuery $.each 循环中创建的 dom 元素?似乎只绑定到最后一个元素!
考虑以下代码,理论上单击事件应该绑定到每个元素,但由于某种原因(我不知道)它只会绑定到最后一个链接。有人有什么想法吗?
$.each(data, function(i,aitem){
linkid = 'address'+i;
$("#SearchResults").html($("#SearchResults").html()+'<p><a id="'+linkid+'" href="#">'+ aitem.Address +'</a></p>');
$('#'+linkid).bind("click", function(){
otherfunction(i);
return false;
});
});
Consider the following code, in theory the click event should bind to each element but for some reason (unbeknown to me) it will only bind to the last link. does anyone have any ideas?
$.each(data, function(i,aitem){
linkid = 'address'+i;
$("#SearchResults").html($("#SearchResults").html()+'<p><a id="'+linkid+'" href="#">'+ aitem.Address +'</a></p>');
$('#'+linkid).bind("click", function(){
otherfunction(i);
return false;
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是刚接触闭包的人的常见问题。
正确的解决方案是这样做:
this is a common problem with people who are new to closures.
the correct solution would be to do this:
尝试:
这个想法是,您希望将单击事件绑定到您正在创建的每个链接,因此只需将其链接到创建代码的末尾,并明确说明即可。
希望有帮助。
try:
The idea being that you want to bind your click event to each link that you are creating, so just chain it to the end of your creation code, and be explicit about it.
Hope that helps.
添加实时点击事件怎么样?
应该向所有这些链接添加点击事件(:
编辑:包含达林的提示...
What about adding a live click-event?
should add a click event to all those links (:
edit: Included tip from darin...