简体   繁体   中英

JavaScript button click should append a input field to it's own div

I get troubles with the EventListeners if I use innerHTML+= to append a new input field, since there is a caching problem I guess.

<div id="frame">

  <input type="button"  id="btn"/>

</div>

JS

   document.getElementById("btn").addEventListener("click",function(){
       divframe.innerHTML+="  <input ... />..."
   });

I simply want if the user presses the button over and over again, there will be a new input and buttons.( with their own EventListeners <- unnecessary right now.)

Instead of ussing innerHTML use appendChild, so the first and the following buttons wont lose his event, and for the new elements you could add onclick event:

<div id="frame">
  <input type="button" value="Add" class="addBtn">
</div>
<script>function appendBtn(){
    var newBtn = document.createElement("input");
  newBtn.onclick = appendBtn;
  newBtn.value = "Add";
  newBtn.classname = "addBtn";
  newBtn.type = "button"
    document.getElementById("frame").appendChild(newBtn);
}

document.getElementsByClassName("addBtn")[0].addEventListener("click",function(){
    appendBtn()
})</script>

You have to create element then append element into div. You can try this:

document.getElementById("btn").addEventListener("click", function() {  
  var div = document.getElementById("frame");   
  var input = document.createElement("INPUT");   
  div.appendChild(input); 
});

Hope this will help!

divframe.innerHTML+=... rewrites inner HTML and removes event listeners (if any) from child elements. You need to addEventListener again. Below is (useless but working) code. Note that only the first button remains clickable because getElementById returns only one (first) element with the same id. As it is said in other answers better use appendChild .

 var divFrame=document.getElementById('frame'); function setListener(){ document.getElementById('btn').addEventListener('click', function(){ divFrame.innerHTML+=divFrame.innerHTML; setListener(); }); } setListener(); 
 <div id="frame"> <input type="button" id="btn" value="click" /> </div> 

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