繁体   English   中英

javascript 中是否有一种简单的方法来测试 IE8 中的“null or not an object”错误

[英]Is there a simple way in javascript to test for “null or not an object” error in IE8

长期以来,我一直信任许多代码示例,这些示例显示了所谓的“安全”检测不可用对象或 object 属性。两个简单的示例包括获取像这样的屏幕的可用/高度...

var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

或者可能是为了确保服务或程序可用,所以我可以采取替代行动,例如...

 if (!window.event) // do something else
 if (!window.XMLHttpRequest) // do something else

我没有进行上述任何测试,而是从 stackoverflow 上的答案中获取它们,通常来自高评价的答案。 然而,当我在 IE8 上运行带有此构造的代码时,脚本将停止,并且调试器将吐出诸如...

'window.event' is null or not an object 
'window.XMLHttpRequest' is null or not an object 
'window.innerWidth' is null or not an object

当然,它们不是“警告”......它们是阻止一切的错误。所以我想没有简单的方法可以在 IE8 中测试这些类型的对象或 object 属性?我想我可以把 try/catch 块包围在每个可能会导致“null or not an object”投诉的代码行,但它肯定会使我的库更大,并且可能更慢。像这样的条件编译结构似乎不太好用.. .

<!--[if gte IE 9 | !IE ]>-->
 // do something only if !IE or IE > 8
<!--<![endif]>-->
// resume normal inclusion? usually not reliably!

因此,在我给出的导致错误的示例中,我能做些什么来让不支持对象的浏览器的代码更安全,只使用普通的 vanilla javascript?

好吧,因为对“in”运算符的支持一直延伸到 IE 5.5(至少根据这篇 MDN 参考文章: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/运算符/in ),你可以尝试这样的事情:

if ('event' in window || 'innerWidth' in window || 'XMLHttpRequest' in window) {

    // Do stuff...

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM