JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

17.3.2 Event Handler Context

17.3.2 Event Handler Context

When you register an event handler by setting a property, it looks as if you are defining a new method on the document element:

e.onclick = function() { /* handler code */ };

It isn’t surprising, therefore, that event handlers are invoked (with one IE-related exception, described below) as methods of the object on which they are defined. That is, within the body of an event handler, the this keyword refers to the event target.

Handlers are invoked with the target as their this value even when registered using addEventListener(). Unfortunately, however, this is not true for attachEvent(): handlers registered with attachEvent()are invoked as functions, and their this value is the global (Window) object. You can work around this with code like this:


*Register the specified handler function to handle events of the specified*type on the specified target. Ensure that the handler will always be*invoked as a method of the target. */ function addEvent(target, type, handler) { if (target.addEventListener) target.addEventListener(type, handler, false); else target.attachEvent("on" + type,

function(event) {

// Invoke the handler as a method of target,

// passing on the event object

return, event);

}); }

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1