I'm trying to call a function with the "onclick" event as so:
<td id="A1" onclick="move()" class="white"></td>
<td id="A2" onclick="move()" class="painted bp"></td>
<td id="A3" onclick="move()" class="white"></td>
In the function itself, i refer to "this":
function move(e){
var myId = this.id;
alert("myId");
}
When I run the whole thing, the alert says 'undefined'. When I try alert(this)
I get [object window].
I'm working with IE9, btw.
Thanks
this
is thewindow
object in your code.You could pass
this
as the parameter.then:
Try using the event target instead to get the dom element you are looking for:
When calling a function from an event handler, its
this
isn't set by the handler (though you can passthis
from the handler per Xdazz's answer, or setthis
per Kyle's answer). Another approach is to extract the sender element from the event object associated with the event:You also must pass the event explicitly:
Note that when the table cell has nested elements they will be the "sender" thus to grab the desired element (which is the table cell) you have to traverse upwards. To avoid all this headache see below how to attach the handlers through code.
Live test case.
That said, better practice would be to bind the click event through code instead of inline - don't mix HTML with JavaScript. To achieve this, have such code:
With the above code in place, you can remove the inline
onclick=
calls from the HTML and keep your original function - thethis
will point to the clicked table cell.Updated fiddle.
Now
this
will refer to thetd
element in yourmove
function.