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
Post a Comment