现在,尽管大多数现代浏览器都支持document.querySelectorAll()
,但是您可能会遇到旧版本Internet Explorer的问题。检查浏览器是否支持功能的明显方法是:
if(document.querySelectorAll){
//some random code
}
但是据我了解,某些浏览器(IE8)不支持某些属性,例如'body *
'。有没有更好的方法来检查document.querySelectorAll('body *')
是否真正起作用?
[document.querySelectorAll
将被抛出任何不受支持的选择器,因此您可以简单地使用try-catch
块。
检查浏览器是否支持,没有try-catch:
function QuerySelectors() {
return (document['querySelector']&&document['querySelectorAll'])!=null;
}
或
function QuerySelectors(){
return typeof(document['querySelector'])=='function'&&typeof(document['querySelectorAll'])=='function';
}
阅读更多> Reference
使用typeof进行检查:
if(typeof(document.querySelectorAll) != 'undefined'){
//some random code
}