且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用JavaScript单击按钮删除div

更新时间:1970-01-01 07:58:48

这就是我想要你想要的。

This is what I THINK you want.

我尽量不对任何东西进行硬编码,但是计算并删除兄弟姐妹
我还删除了所有内联事件处理程序

I try not to hardcode anything but count and remove siblings I have also remove all inline event handlers

$(function() {
  var $original = $('#ValuWrapper'),
    $crossButton = $('#cross'),
    $content = $("#content");

  $content.on("click", ".cross", function() {
    if ($(this).is("#cross")) return false;
    var $cross = $(this);
    $(this).next().slideUp(400, function() {
      $(this).remove();
      $cross.remove();
    });
  });

  $("#repeat").on("click", function() {
    $content.append($crossButton.clone(true).removeAttr("id"));
    $content.append(
      $original.clone(true)
      .hide() // if sliding
      .attr("id",$original.attr("id")+$content.find("button.cross").length)
      .slideDown("slow") // does not slide much so remove if you do not like it
    );
  });

});

#content { height:100%}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="content">
  <button type="button" class="buttonImgTop cross" id="cross">X</button>
  <div id="ValuWrapper"> 
    ...content comes here... <br/>
    ...content comes here... <br/>
  </div>
</div>
<button type="button" class="buttonImg" id="repeat">Add</button>