检查浏览器是否支持JavaScript中的document.querySelectorAll

问题描述 投票:3回答:3

现在,尽管大多数现代浏览器都支持document.querySelectorAll(),但是您可能会遇到旧版本Internet Explorer的问题。检查浏览器是否支持功能的明显方法是:

if(document.querySelectorAll){
    //some random code
}

但是据我了解,某些浏览器(IE8)不支持某些属性,例如'body *'。有没有更好的方法来检查document.querySelectorAll('body *')是否真正起作用?

javascript internet-explorer dom cross-browser document
3个回答
5
投票

[document.querySelectorAll将被抛出任何不受支持的选择器,因此您可以简单地使用try-catch块。


3
投票

检查浏览器是否支持,没有try-catch:

function QuerySelectors() {
  return (document['querySelector']&&document['querySelectorAll'])!=null;
}

function QuerySelectors(){
  return typeof(document['querySelector'])=='function'&&typeof(document['querySelectorAll'])=='function';
}

阅读更多> Reference


-2
投票

使用typeof进行检查:

 if(typeof(document.querySelectorAll) != 'undefined'){
      //some random code
 }
© www.soinside.com 2019 - 2024. All rights reserved.