K
K
Kim_Soal2018-03-10 17:38:28
JavaScript
Kim_Soal, 2018-03-10 17:38:28

js why this behavior?

works:

var inp1 = document.createElement("input");
  var inp2 = document.createElement("input");

  calculate(inp1, inp2);

  div.appendChild(inp1);
  div.appendChild(inp2);
  
  function calculate(test1, test2){
    test1.oninput = function(){
      console.log(this.value);
    }
    test2.oninput = function(){
      console.log(this.value);
    }
  }

does not work:
var inp1 = document.createElement("input");
  var inp2 = document.createElement("input");

  calculate(inp1, inp2);

  div.appendChild(inp1);
  div.innerHTML +="qwe";
  div.appendChild(inp2);
  div.innerHTML +="qwe";



  function calculate(test1, test2){
    test1.oninput = function(){
      console.log(this.value);
    }
    test2.oninput = function(){
      console.log(this.value);
    }
  }

It became interesting why.
It's probably obvious right away to someone.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-03-10
@Kim_Soal

div.innerHTML +="qwe"

The operator is misleading +=you - it seems to you that something is being added to the contents of the div. This is not entirely true - the content of the div is completely overwritten. Accordingly, previously added elements will be removed and replaced with new ones. And you do not bind any handlers to new elements - hence the lack of output to the console.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question