无法使用嵌套按钮删除Jquery插入的div

时间:2011-12-31 20:24:16

标签: jquery

我有一些jquery代码插入这样的div

function popUpBox(){
$(".openBox").click(function(){     
    var id = $(this).attr('id');
    $("#"+id).append('<div class="box1"><div class="button1">Submit</div></div>');
    closeBox();
});
}

function closeBox(){
     $(".button1").click(function(){
          $(".box1").remove();
     });
}

在document.ready上调用popUpBox函数。当然,我有这样的div ...

<div class="openBox" id="id1">Open Box</div>

closeBox()函数似乎没有将remove()事件绑定到按钮。我试图使用bind和parent.remove但无济于事。

1 个答案:

答案 0 :(得分:3)

您的代码有效。问题是单击Submit按钮也会触发父事件处理程序。所以你要删除弹出框,但是立即再添加一个。

阻止stopping the event from bubbling up触发父事件处理程序:

function closeBox(){
     $(".button1").click(function(e){
          e.stopPropagation();
          $(".box1").remove();
     });
}

quirksmode.org has a great article about this

DEMO

也就是说,不是每次都绑定事件处理程序,而是绑定它一次并使用事件委托

function popUpBox(){
    $(".openBox").click(function(){     
        $(this).append('<div class="box1"><div class="button1">Submit</div></div>');

    }).on('click', '.button1', function(e) {
        e.stopImmediatePropagation();
        $(this).closest('.box1').remove();
    });
}

DEMO