简体   繁体   中英

Adding a button that removes itself and the line it is attached to

I'm not very advanced in javascript. I've been trying to write a script that adds a line of text, along with a button that removes itself and the attached line of text. While I have managed the text part without problem I am having a lot of problem with the button. Whenever I try to add the function that removes the elements to the button, the script keeps working but the created elements never appear(it seems that the button immediately deletes itself and the text, which shouldn't happen without being clicked).

 var numberId=0; function add(){ console.log("add"); var te = document.getElementById("textInput").value; var d=document.createElement("tekst"); var bu=document.createElement("button"); var t=document.createTextNode(te); d.appendChild(t); d.id="a"+numberId; document.getElementById("hereGoesResult").appendChild(d); d.appendChild(bu); function placeholderFunction(){ console.log("placeholder"); deletusTheTextus(d.id); } but.addEventListener("click",placeholderFunction()); numberId++; } function deletsTheText(a){ console.log("delets"); var elem = document.getElementById(a); elem.remove(); } 
  <!DOCTYPE html> <html> <head> <meta http-equiv = "Content-type" charset = "utf-8"> <title > Sample HTML5 File</title> <script src="scripts.js"> </script> </head> <body> <form> Enter: <input type="text" id="textInput"> <input type="button" value="Add" onclick="add()"><br> </form> <div id="hereGoesResult"> </div> </body> </html> 

Sorry for mistakes, I'm posting for the first time (variables have bad names because I had to quickly edit them, my usual ones are a little too silly for being posted on stackoverflow)

Don't call your placeholderFunction while trying to register it as event handler. So this:

but.addEventListener("click", placeholderFunction())

should look like this:

but.addEventListener("click", placeholderFunction);

Next thing is, you write bu for your button variable but try to attach and eventlistener to but . Also make sure you call deletsTheText inside placeholderFunction , not deletusTheTextus ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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