Latest Update: The issue seems to stem from the use of attachEvent
. According to information obtained from quirksmode.org:
In certain scenarios, the reference of 'this' points to the window object:
element.onclick = function () {doSomething()}
element.attachEvent('onclick',doSomething)
<element onclick="doSomething()">
It is worth noting the usage of attachEvent()
. The main drawback associated with the Microsoft event registration model is that attachEvent()
only creates a reference to the function rather than copying it. This can pose difficulty in determining which HTML element currently handles the event.
To resolve this issue, creating a wrapper like the one below may be necessary:
var addListener = (function() {
if(document.attachEvent) {
return function(element, event, handler) {
element.attachEvent('on' + event, function() {
var event = window.event;
event.currentTarget = element;
event.target = event.srcElement;
handler.call(element, event);
});
};
}
else {
return function(element, event, handler) {
element.addEventListener(event, handler, false);
};
}
}());
With this approach, this
would now refer to the specific element, similar to event.currentTarget
, and you would pass event
as the initial argument.
Here's how you could utilize this solution:
addListener(element, 'click', function(e) {
// 'this' points to the specific element
// e.currentTarget indicates the current element
// e.target represents the element that triggered the event
});
Prior Response: (applicable for both inline and traditional event handlers, along with addEventListener
but not attachEvent
)
Within the event handler, using this
will directly target the element assigned to the event handler.