examples of ie obj.attachEvent()

南笙酒味 提交于 2019-12-23 03:10:29

问题


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.


回答1:


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




回答2:


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);
}


来源:https://stackoverflow.com/questions/5728509/examples-of-ie-obj-attachevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!