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

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -