我在删除使用 javascript 添加的段落时遇到问题。添加按钮效果很好。当我尝试删除该段落时出现问题。function rdn_id(){return Math.random().toString(36).substring(7);}//create buttonfunction 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 functionfunction 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 functionfunction 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>
1 回答
慕姐8265434
TA贡献1813条经验 获得超2个赞
您需要进行两项更改:
事件名称应该
click
代替onclick
elt.parentNode.removeChild(id_el);
应该elt.parentNode.removeChild(elt);
看看这支笔 https://codepen.io/tanmayv/pen/yLNwNNJ
- 1 回答
- 0 关注
- 72 浏览
添加回答
举报
0/150
提交
取消