使用jQuery.append时绑定事件丢失
我有这样一个简单的代码使用jQuery.append时绑定事件丢失,jquery,jquery-events,dom-manipulation,Jquery,Jquery Events,Dom Manipulation,我有这样一个简单的代码 $(函数(){ $('body')。追加( $(“这应该行得通,对吧?这一个行得通: $(function(){ // Add the click event for all future elements having the id #foo $('#foo').live("click",function(e){ e.preventDefault(); alert("Hello Wo
$(函数(){
$('body')。追加(
$(“这应该行得通,对吧?这一个行得通:
$(function(){
// Add the click event for all future elements having the id #foo
$('#foo').live("click",function(e){
e.preventDefault();
alert("Hello World!");
});
$('body').append(
$("<a/>").attr({ "id": "foo", "href":"#" })
.text("Continue ")
);
});
$(函数(){
//为id为#foo的所有未来元素添加单击事件
$('#foo').live(“单击”,函数(e){
e、 预防默认值();
警报(“你好,世界!”);
});
$('body')。追加(
$(“”).attr({“id”:“foo”,“href”:“#”})
.文本(“继续”)
);
});
DOM遍历方法不是
支持查找要发送的元素
而不是.live()方法
应始终在之后直接调用
选择器,如上面的示例所示
因此,代码中唯一的问题是使用live()
“
不是选择器,而且live()
的工作方式无法找到相应的元素。如果只使用。click()
,它当然可以完美地工作
你可以用像
$('body')
.append(
$("<a/>")
.attr({ "id": "foo", "href":"#" })
.text("click me")
)
)
.delegate("#foo", "click", function(e){
e.preventDefault();
alert("Hello World!");
});
$(“正文”)
.附加(
$("")
.attr({“id”:“foo”,“href”:“#”})
.text(“单击我”)
)
)
.delegate(“#foo”,“click”,函数(e){
e、 预防默认值();
警报(“你好,世界!”);
});
要实现您想要的(但我认为根据您的使用情况,简单的单击()
就足够了)。第e行出现语法错误。preventDefault()。放一个逗号:)抱歉..键入错误,但这不是问题。。
$('body')
.append(
$("<a/>")
.attr({ "id": "foo", "href":"#" })
.text("click me")
)
)
.delegate("#foo", "click", function(e){
e.preventDefault();
alert("Hello World!");
});