I've come across a head scratching issue with my JavaScript application.
If I write an element like this:
<li onClick="alert(this.tagName)"></li>
I get "LI."
However if I do this:
<li onClick="foo()"></li>
Where "foo()" is:
function foo(){ alert(this.tagName); }
I get "undefined."
I am away how "this" is supposed to work in regards to attached functions. But, I am baffled because "this" is not picking up the element, but apparently defaulting to "window." I can't figure out why this is happening.
Does anyone have an explanation?
onclick = doSomething; The function is copied in its entirety to the onclick property (which now becomes a method). So if the event handler is executed this refers to the HTML element and its color is changed. Thus you use this to the fullest extent.
The onclick event generally occurs when the user clicks on an element. It allows the programmer to execute a JavaScript's function when an element gets clicked. This event can be used for validating a form, warning messages and many more. Using JavaScript, this event can be dynamically added to any element.
If you called onclick ( element. onclick() ), you'd call the function attached to it — but not handlers attached with modern methods. E.g., click triggers a fake click; the other lets you set up a handler for clicks.
The onclick event is a DOM event that occurs when a user clicks on an element. The Document Object Model (DOM) is created by the browser when a web page is loaded. This is a data structure representing the page as a series of nodes and objects.
That's because you aren't passing a reference to this in the JavaScript function call. this in the JavaScript function doesn't refer to the same object as in the onClick example. Try this instead:
<li onClick="foo(this)"></li>
function foo(item){ alert(item.tagName); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With