使用 jQuery.append 时绑定事件会丢失
我有一个像这样的简单代码 http://jsfiddle.net/9braK/2/
$(function(){
$('body').append(
$("<a/>").attr({ "id": "foo", "href":"#" })
.text("click me")
.live("click",function(e){
e.preventDefault();
alert("Hello World!");
})
);
});
根据docs 这应该有效,对吧?
I have a simple code like this http://jsfiddle.net/9braK/2/
$(function(){
$('body').append(
$("<a/>").attr({ "id": "foo", "href":"#" })
.text("click me")
.live("click",function(e){
e.preventDefault();
alert("Hello World!");
})
);
});
According to the docs this should work, right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
来源
所以代码中唯一的问题是
live()
的使用。""
不是选择器,并且live()
的工作方式将无法找到相应的元素。如果您只是使用.click()
,它当然可以完美地工作。您可以使用类似的方法
来实现您想要的(但我认为根据您的用例,简单的
click()
就足够了)。Source
So the only problem in your code is the usage of
live()
."<a/>"
is not a selector, and the waylive()
works it won't be able to find corresponding elements. If you simply use.click()
, it will work flawlessly of course.You can use something like
to achieve what you wanted (but I think a simple
click()
would be sufficient depending on your use case).这个有效:
This one works :