【问题标题】:Something is wrong with remove() function in jQuery [duplicate]jQuery 中的 remove() 函数有问题[重复]
【发布时间】:2016-02-09 07:36:09
【问题描述】:
<script>
$(document).ready(function(){
    var i = <?=$iMaxId?>;
    var c = 0;
    $('#addphone').click(function(){
        i += 1;
        c += 1;
        var sTag = "<div class='trow' id='Phone"+i+"'><div>Phone No. </div><div><input type='text' name='sPhone[]' ><input type='button' value='delete' class='delete' id='"+i+"'></div></div>";
        $('#imgfield').last().before(sTag);
    });


    $(".delete").click(function()
    {
        var iId = $(this).attr("id");;
        $("#Phone" + iId).remove( );
    });
});
</script>

此脚本完美地添加了输入字段,但在单击删除按钮时无法删除它们。

【问题讨论】:

  • 在线提供代码
  • 您很可能会在创建输入字段之前尝试附加删除功能。因此,新插入的输入字段没有附加删除处理程序。使用 JQuery 提供的实时事件 (live())
  • “jqeury 中的 remove() 函数有问题” - 或者,您的代码可能有问题...跨度>

标签: javascript jquery


【解决方案1】:

更新您的删除功能,如

$("body").on("click",".delete", function()
    {
        var iId = $(this).attr("id");;
        $("#Phone" + iId).remove( );
    });

【讨论】:

【解决方案2】:
$(".delete").click(function() {
    var iId = $(this).attr("id");;
    $("#Phone" + iId).remove( );
});

此代码 sn-p 立即运行。 $(".delete") 选择器选择当前存在于文档中且类名为“delete”的所有元素,并为这些元素设置单击事件侦听器。但是,具有“删除”类的动态添加按钮将没有此侦听器,因为它们以前没有被选中,因为它们以前不存在。

让它工作的一种方法是将设置点击侦听器的代码放在#addphone点击回调函数中,即

$(document).ready(function(){
    var i = <?=$iMaxId?>;
    var c = 0;
    $('#addphone').click(function(){
        i += 1;
        c += 1;
        var sTag = "<div class='trow' id='Phone"+i+"'><div>Phone No. </div><div><input type='text' name='sPhone[]' ><input type='button' value='delete' class='delete' id='delete"+i+"'></div></div>";
        $('#imgfield').last().before(sTag);

        $("#delete" + i).click(function() {
            var i = $(this).attr("id").replace("delete", "");
            $("#Phone" + i).remove();
        });
    });

});

顺便说一句,您不应该使用纯数字作为 ID。它在 HTML4 中是不允许的。有些浏览器可能会抱怨。

【讨论】:

    【解决方案3】:

    这对你来说可能很好

    $(document).on('click','.delete',function(){
        $(this).parents('.trow').remove();
    })
    

    【讨论】:

      猜你喜欢
      • 2011-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多