I'm tired of writing jQuery, so I decide to learn some raw JavaScript.
Something in IE's attachEvent
confused me. Here's the code:
var btn = document.getElementById('myBtn');
btn.onclick = function(){
alert(window.event.srcElement === this); //true, I know why.
};
btn.attachEvent('onclick', function(event){
alert(event.srcElement === this); //fasle, but why?
});
I try to use IE's built-in debug tools, but it just told me that 'this' is an object, but nothing more...
so what's 'this' in IE's attachEvent
?
I'm tired of writing jQuery, so I decide to learn some raw JavaScript.
Something in IE's attachEvent
confused me. Here's the code:
var btn = document.getElementById('myBtn');
btn.onclick = function(){
alert(window.event.srcElement === this); //true, I know why.
};
btn.attachEvent('onclick', function(event){
alert(event.srcElement === this); //fasle, but why?
});
I try to use IE's built-in debug tools, but it just told me that 'this' is an object, but nothing more...
so what's 'this' in IE's attachEvent
?
-
try outputting
this
to the console and see. useconsole.log(this)
– Joseph Commented Feb 9, 2012 at 2:56 - I try that, but IE just told me it's an object, nothing more. – shawjia Commented Feb 9, 2012 at 2:58
- 1 did you spot the typo "srcElemnt"? Without the "e" that event property will be undefined (and !== this). – Bergi Commented Feb 9, 2012 at 2:58
- just a typo, fixed.still return false. – shawjia Commented Feb 9, 2012 at 3:03
3 Answers
Reset to default 7Within an event handler bound by the IE-specific attachEvent
method, this
refers to the global window
object:
btn.attachEvent('onclick', function(event) {
alert(this === window); // true
}
In contrast, within an event handler bound by the standard addEventListener
method, this
refers to the DOM element from which the event handler was triggered.
this is a context reference and is referencing window when the the click event occurs, because that is the only context that exists at that time.
I think U misspell one word.
btn.attachEvent('onclick', function(event){
alert(event.**srcElement** === this);
});
And I tested the corresponding function addEventListener in chrome and ff, they both returned true.
IE do returns false. Maybe because IE deal with btn.onclick=fn; and btn.attachEvent() with different way. IE passes global value(window) to the btn.attachEvent() method. You can test this=== window , it returns true.
Any ments about it?
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744976168a4604155.html
评论列表(0条)