Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第57题(2019-10-14):编写一个 JavaScript 函数,输入指定类型的选择器 ( 仅需支持 id , class ,tagName 三种简单 CSS 选择器,无需兼容组合选择器 ) 可以返回匹配的 DOM 节点,需考虑浏览器兼容性和性能。 #59

Open
qappleh opened this issue Oct 14, 2019 · 1 comment
Labels

Comments

@qappleh
Copy link
Owner

qappleh commented Oct 14, 2019

No description provided.

@qappleh
Copy link
Owner Author

qappleh commented Oct 15, 2019

/**

  * @param selector {String}  传入的 CSS 选择器。 

  * @return {Array}

  */  
var query = function(selector) {
   var reg = /^(#)?(\.)?(\w+)$/img;
   var regResult = reg.exec(selector);
   var result = []; 
   //如果是id选择器 
   if(regResult[1]) {
     if(regResult[3]) {
       if(typeof document.querySelector === "function") {
         result.push(document.querySelector(regResult[3]));
       } else {
         result.push(document.getElementById(regResult[3]));                         
         }
       }
     }
     //如果是class选择器                
     else if(regResult[2]) {
       if(regResult[3]) {
         if(typeof document.getElementsByClassName === 'function'{                             
         var doms = document.getElementsByClassName(regResult[3]);        
         if(doms) {
           result = converToArray(doms);3        
         }
       }
       //如果不支持getElementsByClassName函数                       
       else {
         var allDoms = document.getElementsByTagName("*");
         for(var i = 0, len = allDoms.length; i < len; i++) {
           if(allDoms[i].className.search(new RegExp(regResult[2])) > -1) {
              result.push(allDoms[i]);
           }
         }
       }
     }
   }
   //如果是标签选择器37                 
   else if(regResult[3]) {
     var doms = document.getElementsByTagName(regResult[3].toLowerCase());
      if(doms) {
         result = converToArray(doms);
      }
    }
  return result;
}
function converToArray(nodes){
  var array = null;
  try {
    array = Array.prototype.slice.call(nodes,0);//针对非IE浏览器     
  }catch(ex) {
    array = new Array();
    for(var i = 0 ,len = nodes.length; i < len ; i++ ) {
      array.push(nodes[i])
    }
  }
  return array;
}  

@qappleh qappleh added the js label Nov 27, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant