JavaScript:检测IE的最佳方法 [英] JavaScript: The best way to detect IE

查看:108
本文介绍了JavaScript:检测IE的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

阅读这篇文章我发现了以下一段代码:

Reading this article I've found a following piece of code:

if ('v'=='\v') { // Note: IE listens on document
    document.attachEvent('onstorage', onStorage, false);
}

此方法'v'=='\ \v'一个好主意?这是检测IE的最短方法吗?

Is this method 'v'=='\v' a great idea? Is this the shortest way to detect IE ever?

推荐答案

如果可以避免的话,请不要测试浏览器。做特征检测。这意味着您的代码(很有可能)是面向未来的。例如,在这种情况下,如果您发现浏览器是IE,并因此决定使用 attachEvent ,则您会错过 addEventListener (上级)。

If you can avoid it, don't test for browsers. Do feature detection. This will mean that your code is (more likely to be) future-proof. In this case, for instance, if you discovered that the browser was IE and decided to use attachEvent because of it, you would miss out on the fact that addEventListener (superior) is available in IE9.

在这种情况下,请测试是否 document.addEventListener 存在。如果是,那么您就有了答案。

In this case, test to see if document.addEventListener exists. If it does, you have the answer.

if (document.addEventListener) {
    document.addEventListener(...);
} else {
    document.attachEvent(...);
}






编辑:duri上面的评论显示该测试在IE9中失败(按照标准),这实际上意味着它是 addEventListener 的理想测试,因为它可以从IE9获得。 但是对于特定功能而不是特定浏览器进行编程仍然要好得多。


duri's comment above shows that this test fails in IE9 (as per standards), which actually means it is a perfect test for addEventListener, since that is available from IE9. However it is still far, far better to program for specific functionality, rather than specific browsers.

这篇关于JavaScript:检测IE的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆