javascript - JS - How to add an onclick event to a div with parameter? -


i know how add onclick event div without parameter :

newdiv.onclick = selectunit;  function selectunit() {} 

but not make work parameters :

function appendunit(nb) {     var newdiv = document.createelement("div");      newdiv.id = "unit" + nb;     newdiv.onclick = selectunit(this.id); // throws me undefined     document.getelementbyid("unitslist").appendchild(newdiv); }  function selectunit(id) {     console.debug(id); } 

how can ?

you'll need anonymous function that, there no way pass arguments referenced function

function appendunit() {     var newdiv = document.createelement("div");      newdiv.onclick = function() {         selectunit(this.id);     }      document.getelementbyid("unitslist").appendchild(newdiv); }  function selectunit(id) {     console.debug(id); } 

but note value of this keep, can

function appendunit() {     var newdiv = document.createelement("div");      newdiv.onclick = selectunit;      document.getelementbyid("unitslist").appendchild(newdiv); }  function selectunit() {     console.debug( this.id ); // still same here } 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -