在Javascript Dom中,新添加的元素不能被选中

in Javascript Dom ,the newly added element can't be selected?

本文关键字:元素 不能 添加 Dom Javascript 新添加      更新时间:2023-09-26
<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解决这个<一口>[医生].delegate <一口>[医生]:

$(".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();