2011-12-31 46 views
0

我有一些jQuery代码中插入一个div像这样无法删除的Jquery使用嵌套按钮

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(); 
    }); 
} 

功能popUpBox被称为上的document.ready插入DIV。当然,我有这样一个div ...

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

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

+0

代替'变种的id = $(this).attr('id'); $(“#”+ id).append(...);'你可以写'$(this).append(...);'。 – 2011-12-31 20:26:16

+0

你的代码片段缺少第4行上的'''char字符 – rabusmar 2011-12-31 20:27:02

+0

你缺少''' – 2011-12-31 20:27:44

回答

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

+0

美丽。谢谢。 – buck54321 2011-12-31 20:35:20