最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - attachEvent Doesn't work in IE > 8.0 - Stack Overflow

programmeradmin2浏览0评论

I'm using attachEvent for a while, but it seems that IE doesn't support this anymore?

window.attachEvent("onload",Start_Wysiwyg);
window.attachEvent("onscroll",ScrollEditBar,false);

Does anyone have a solution for this problem?

I'm using attachEvent for a while, but it seems that IE doesn't support this anymore?

window.attachEvent("onload",Start_Wysiwyg);
window.attachEvent("onscroll",ScrollEditBar,false);

Does anyone have a solution for this problem?

Share Improve this question asked Nov 24, 2013 at 19:44 FreexelFreexel 1271 gold badge1 silver badge6 bronze badges 2
  • 3 Instead, use addEventListener in IE 9,10,11 – Givi Commented Nov 24, 2013 at 19:46
  • 3 possible duplicate of addEventListener in internet explorer – MartyIX Commented Nov 24, 2013 at 19:56
Add a comment  | 

1 Answer 1

Reset to default 16

.attachEvent() is deprecated in IE9+, and has been removed in IE11.

The standard is .addEventListener() (MSDN docs). The MDN docs have a section about compatibility.

You can simply run some feature-checking code to check if the supported features exist:

if (window.addEventListener) {
    // Check for addEventListener first, since IE9/10 have both,
    // but you should use the standard over the deprecated IE-specific one
    window.addEventListener('click', myFunc);
} else if (window.attachEvent) {
    window.attachEvent('onclick', myFunc);
}

If you have to attach a lot of event listeners, then you may want to just cache the desired listener attachment method in a variable and use that variable for attaching your events throughout your code, rather than having that above check for every single event listener:

var addListener = function(){}; // Default to no-op function

if (window.addEventListener) {
    addListener = window.addEventListener;
} else if (window.attachEvent) {
    addListener = function(eventType, listener, useCapture) {
        // attachEvent wants 'oneventType' instead of 'eventType'
        window.attachEvent('on'+eventType, listener, useCapture);
    };
}

// Now you can add listeners with a browser-agnostic function call!
addListener('click', myFunc);
addListener('hover', myOtherFunc);

You can read more in a duplicate question linked by @MartyIX in a comment on your question. There are further nuances and methods in the answers/comments there, such as IE9 requiring <!DOCTYPE html> in order to use .addEventListener().

发布评论

评论列表(0)

  1. 暂无评论