简体   繁体   English

如何删除 HTML 克隆元素

[英]How to remove HTML clone element

What I am trying to create is basically a close button for a cloned form.我要创建的基本上是克隆表单的关闭按钮。 The form along with the close button is generated onclick() using the following function:使用以下 function 生成 onclick() 表单以及关闭按钮:

$("#newVolton").click(function(){   
  var index = 0;
  $("#border").clone().attr('id', 'volton' + index).appendTo("#border");
  index++;
});

and I want to be able to close said form using the button that is generated alongside the specific instance of the form.并且我希望能够使用与表单的特定实例一起生成的按钮来关闭所述表单。

How should I got about deleting the instance?我应该如何删除实例?

Thanks in advance!提前致谢!

I prefer to delegate我更喜欢委托

Make a main container and append to that Then each div has its own HTML and a delete button.制作一个主容器和 append 然后每个 div 都有自己的 HTML 和一个删除按钮。

Note I hide the first delete to allow the clone source to stay注意我隐藏了第一个删除以允许克隆源保留

You can change it to a template if you do not want to have an initial div如果您不想拥有初始 div,可以将其更改为模板

 $("#newVolton").on("click",function() { const $borders = $("#container").find(".border"); const idx = $borders.length; // count the existing number of divs $borders.eq(0).clone().attr('id', 'volton' + idx).appendTo("#container"); }); $("#container").on("click",".remove",function() { this.closest("div").remove() });
 #container>div.border span.remove { display: none } #container>div.border~div.border span.remove { display: inline-block }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button type="button" id="newVolton">Add</button> <div id="container"> <div class="border" id="volton0"> Some html <span class="remove">X</span> </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM