使用Jquery从DOM中删除元素

时间:2015-09-02 12:04:53

标签: jquery

我有一些静态div和jquery添加了一些div 我需要一个“删除元素”按钮 我使用Jquery从DOM中删除元素 我的问题是我只能删除静态元素,而不是“稍后添加jquery”。

我该如何解决这个问题? 小提琴: http://jsfiddle.net/7hqu377v/3/

HTML

<div class="col-md-1">
  <button class="btn btn-success" id="btnAddFlak">+ Flak</button>
</div>
<div class="well" id="flakDiv"> <span class="deleteFlak pull-right">x</span>
  <div class="flak nopadding">
    <div class="flakSideUp nopadding"></div>
    <div class="flakMiddle">Flak <b><span>1</span></b>
    </div>
    <div class="flakSideDown nopadding"></div>
  </div>
</div>

JS

var flakNr = 1;
//Create flak
$('#btnAddFlak').on('click', function () {

    //Set flakNr
    flakNr = $('.flakMiddle').last().find("span").text();
    if (isNaN(flakNr)) flakNr = 1;


    //Increase flakNr
    flakNr++;

    //Flak HTML setup
    var flak = $('<span class="deleteFlak pull-right">x</span><div class="flak nopadding"><div class="flakSideUp nopadding"></div><div class="flakMiddle">Flak <b><span>' + flakNr + '</span></b></div><div class="flakSideDown nopadding"></div></div><br>');

    //Insert flak to flakDiv
    $('#flakDiv').append(flak);
  });

  //Delete flak
  $('.deleteFlak').on('click', function () {

  //Remove flak from DOM
  $(this).next('.flak').remove();
  $(this).remove();

}); //END Delete flak

3 个答案:

答案 0 :(得分:4)

问题在于event delegation动态添加的对象。

DEMO

//Delete flak
$(document).on('click', '.deleteFlak', function () {

    //Remove flak from DOM
    $(this).next('.flak').remove();
    $(this).remove();

}); //END Delete flak

答案 1 :(得分:1)

每当您需要访问稍后通过javascript添加的元素时,请通过$(document)访问它们,如下所示:

$(document).on('click', '.deleteFlak', function () {
//Remove flak from DOM
  $(this).next('.flak').remove();
  $(this).remove();

}); //END Delete flak

答案 2 :(得分:0)

创建元素后,您应该绑定事件。

我复制你的代码,在创建新元素后,我重新绑定了click envents。

var flakNr = 1;
//Create flak
$('#btnAddFlak').on('click', function () {

    //Set flakNr
    flakNr = $('.flakMiddle').last().find("span").text();
    if (isNaN(flakNr)) flakNr = 1;


    //Increase flakNr
    flakNr++;

    //Flak HTML setup
    var flak = $('<span class="deleteFlak pull-right">x</span><div class="flak nopadding"><div class="flakSideUp nopadding"></div><div class="flakMiddle">Flak <b><span>' + flakNr + '</span></b></div><div class="flakSideDown nopadding"></div></div><br>');

    //Insert flak to flakDiv
    $('#flakDiv').append(flak);

   // here you should remove the older 'click' events. And create new events for ALL. Because the events are only attached to the oldest elements
    $('.deleteFlak').unbind('click').click(function () {
          //Remove flak from DOM
          $(this).next('.flak').remove();
          $(this).remove();
    }); //END Delete flak
});

  //Delete flak
$('.deleteFlak').click(function () {
      //Remove flak from DOM
      $(this).next('.flak').remove();
      $(this).remove();
}); //END Delete flak