我在刪除使用 javascript 添加的段落時(shí)遇到問題。添加按鈕效果很好。當(dāng)我嘗試刪除該段落時(shí)出現(xiàn)問題。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貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
您需要進(jìn)行兩項(xiàng)更改:
事件名稱應(yīng)該
click
代替onclick
elt.parentNode.removeChild(id_el);
應(yīng)該elt.parentNode.removeChild(elt);
看看這支筆 https://codepen.io/tanmayv/pen/yLNwNNJ
- 1 回答
- 0 關(guān)注
- 122 瀏覽
添加回答
舉報(bào)
0/150
提交
取消