简体   繁体   中英

onchange element.appendChild again and again

<p class="label">
  <form id="links">
    <input type="text" class="insert" name="input" onchange="createLink()">
    <br>
  </form>
</p>
</div>
<script>
 function createLink() {
   var newline = document.createElement("br");
   var input = document.createElement("input");
   input.type = "text";
   input.name = "input";
   input.onchange = "createLink()";
   var element = document.getElementById("links");
   element.appendChild(newline);
   element.appendChild(input);
 }

</script>



I tried to repeat create a new input field again from the new input field, but its only possible from my first input field. Why? And whats the best solution

Use this code. I hope this code work you mean )

<p class="label">
      <form id="links">
          <input type="text" class="insert" name="input" onchange="createLink()"><br>
      </form>
</p>

<script>
    var element = document.getElementById("links");
    
    function createLink(){
      var newline = document.createElement("br");
      var input = document.createElement("input");
      input.type = "text";
      input.name = "input";
      input.addEventListener('change', createLink)

      element.appendChild(newline);
      element.appendChild(input);
    }
</script>

Your Implementation is a little bit off the mark.Instead of passing the createLink as string. pass it as arrow function, as shown below:

<p class="label">
  <form id="links">
    <input type="text" class="insert" name="input" onchange="createLink()">
    <br>
  </form>
</p>
</div>
<script>
 function createLink() {
   var newline = document.createElement("br");
   var input = document.createElement("input");
   input.type = "text";
   input.name = "input";
   
   input.onchange = ()=> createLink();
   var element = document.getElementById("links");
   element.appendChild(newline);
   element.appendChild(input);
 }

</script>

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