简体   繁体   English

如何使用javascript动态添加删除块

[英]How to dynamically add remove block using javascript

I am facing a problem while removing a paragraph, which I have added using javascript.我在删除段落时遇到问题,这是我使用 javascript 添加的。 Adding buttons work fine.添加按钮工作正常。 The problem occurs when I try to remove the paragraph.当我尝试删除段落时会出现问题。

 function rdn_id(){return Math.random().toString(36).substring(7);} //create button function create_btn() { //Create a remove button var btn_remove = document.createElement("BUTTON"); //create a unique button ID id_btn_remove = rdn_id(); btn_remove.id = id_btn_remove ; btn_remove.textContent = "Remove file"; return [btn_remove, id_btn_remove]; } //add elt function function create_p_btn() { //Create paragraph var paragraph = document.createElement("P"); //create a unique p ID id_paragraph = rdn_id(); paragraph.id = id_paragraph; paragraph.style.paddingTop = "5px"; paragraph.style.background = "blue"; document.getElementById("setItHere").appendChild(paragraph); // add button var values = create_btn(); var btn_rmv = values[0]; var id_btn = values[1]; paragraph.appendChild(btn_rmv); document.getElementById(id_btn).addEventListener("onclick", function(){remove_func(id_paragraph);}); } //Remove function function remove_func(id_el) { var elt = document.getElementById(id_el); elt.parentNode.removeChild(id_el); }
 <div id="setItHere"> <Button id="start" onclick="create_p_btn();">add</Button> </div>

Am I missing something ?我错过了什么吗? Thank you in advance.先感谢您。

You need to make two changes:您需要进行两项更改:

  1. Event name should be click instead of onclick事件名称应该是click而不是onclick
  2. elt.parentNode.removeChild(id_el); should be elt.parentNode.removeChild(elt);应该是elt.parentNode.removeChild(elt);

Check out this pen https://codepen.io/tanmayv/pen/yLNwNNJ看看这支笔https://codepen.io/tanmayv/pen/yLNwNNJ

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

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