[英]in Javascript Dom ,the newly added element can't be selected?
<body>
<div id="options">
<p class="input">
<input type="text"/>
<a class="remove" >Remove</a>
</p>
<p class="input">
<input type="text"/>
<a class="remove" >Remove</a>
</p>
</div>
<a href = "#" id ="click" >Add Option</a>
</body>
和:
$(function() {
$("#click").click(function add_option(){
var options = document.getElementById("options");
var p=document.createElement("p");
p.setAttribute("class","input");
var input=document.createElement("input");
input.setAttribute("type","text")
options.appendChild(p);
p.appendChild(input);
var a=document.createElement("a");
a.setAttribute("class","remove");
var text = document.createTextNode(" Remove");
a.appendChild(text);
insertAfter(a,input);//if exist insertAfter
}
)
$(".remove").click(function remove_option(){
$(this).parent().remove();
})
})
当我单击Add Option
,它起作用,但是当我单击新添加的remove
时,它不会删除。$(“。remove”)选择器是否对它有影响?(最初的两个remove
)。如何使新添加的元素起作用?
尝试与.live()
$(".remove").live("click",function(){
$(this).parent().remove();
});
在将事件处理程序绑定到.remove
元素时,新元素尚不存在(显然)。 这就是jQuery无法找到它们并绑定事件处理程序的原因。
您可以使用.live
[docs]或.delegate
[docs]解决此问题:
$(".remove").live('click', function(){
$(this).parent().remove();
});
这些方法将事件处理程序绑定到文档根目录,并检查每个click
事件(在这种情况下),并测试目标是否与选择器匹配。 如果是,则执行处理程序。
我还建议您不要将纯DOM操作和jQuery这样混合使用。 您的click
事件处理程序可以用更简洁的方式编写:
$("#click").click(function(){
$('<p />', {'class': 'input'})
.append($('<input />', {type: 'text'})
.append($('<a />', {'class': 'remove', href: '#', text: 'Remove'})
.appendTo('#options');
});
有一些例外,例如访问DOM元素的属性,但是在这里您确实应该使用jQuery。
这有效: http : //jsfiddle.net/UJERQ/
$("#click").click(function add_option(){
$("#options").append('<p class="input"><input type="text"/><a class="remove" > Remove</a></p>')
addTheClicks();
})
function addTheClicks(){
var btns = $(".remove");
var btnsLength = btns.length;
for(i=0;i<btnsLength;i++){
var hasClickAlready = $.data(btns.eq(i).get(0), 'events' );
if(hasClickAlready == null){
btns.eq(i).click(function(){
$(this).parent().remove()
})
}
}
}
addTheClicks();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.