javascript - onClick Function "this" Returns Window Object -


i've come across head scratching issue javascript application.

if write element this:

<li onclick="alert(this.tagname)"></li> 

i "li."

however if this:

<li onclick="foo()"></li> 

where "foo()" is:

function foo(){ alert(this.tagname); } 

i "undefined."

i away how "this" supposed work in regards attached functions. but, baffled because "this" not picking element, apparently defaulting "window." can't figure out why happening.

does have explanation?

that's because aren't passing reference this in javascript function call. this in javascript function doesn't refer same object in onclick example. try instead:

 <li onclick="foo(this)"></li>   function foo(item){ alert(item.tagname); } 

Comments

Popular posts from this blog

sql - Time in datatime field -

javascript - How to split the success output from an Ajax post? -

java - sharing object across different classes -