javascript - Value of variable to event listener -


task simple, experience not enough solving it. need use outer variable in eventlistiner. if try use outer variable, "undefined". seems solved closures, can't understand how works.

wrong code:

function myfunc(){     title = "head";     console.log(title);//head     document.getelementbyid("test").onclick = function(){         console.log(title);//undefined     }  } 

right code:

function myfunc(){     title = "head";     console.log(title);//head     document.getelementbyid("test").onclick = function(){         //some magic...         console.log(title);//head     }  } 

hope help. thanks.


unfortunetly yours answers don't help. have tryed, if easy not write here. still, have made yourself:

function myfunc(){             function cls(it){                 return function(){                     console.log(it);                 }             }             title = "head";             document.getelementbyid("test").addeventlistener("click",cls(title), false);//head     } 

thank you, atleast tried help, , minuses too.

pull title out of myfunc():

var title = "head"; function myfunc() {   document.getelement... } 

Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -