examples of ie obj.attachEvent()

2019-06-03 10:16发布

does anyone know how works the obj.attachEvent on ie?

I tried a few examples but they don't work. Also is this compatible with ie7?

What i tried is this :

var onload = function( ) {
        console.log("intercepting: " + this.status + " " + this.responseText);
    };

if($.browser.msie){
   console.log("it's IE...");
   this.attachEvent("load", onload);
}

All above inside an XMLHtppRequest.

2条回答
姐就是有狂的资本
2楼-- · 2019-06-03 10:32

For attachEvent, you need to prefix the event name with "on", e.g.

this.attachEvent("onload", onload);

This differs from the DOM Events' addEventListener, which requires the "on" to be omitted.

As Marcel pointed out, for XMLHttpRequests you need to bind to onreadystatechange instead, and check the readyState property inside the handler. onload isn't supported for XMLHttpRequest.

On another note, you should avoid checking the browser and check feature support instead. Internet Explorer 9 supports addEventListener, for instance:

var onreadystatechange = function( ) {
    if (this.readyState == 4)
        console.log("intercepting: " + this.status + " " + this.responseText);
};

if(!this.addEventListener && this.attachEvent){
   console.log("it's IE<9...");
   xhr.attachEvent("onreadystatechange", onreadystatechange);
}
else
    // use addEventListener

In reality though, you wouldn't use attachEvent or addEventListener on an XHR object; I doubt IE7 and lower will play nice with this, so you would just bind to the event property directly:

xhr.onreadystatechange = function () {
    if (this.readyState == 4)
        console.log("intercepting: " + this.status + " " + this.responseText);
}
查看更多
对你真心纯属浪费
3楼-- · 2019-06-03 10:44

You probably want to assign that function to xhrObject.onreadystatechange.

查看更多
登录 后发表回答