2010-10-04 32 views

回答

3

使用jQuery?或者至少有一个像Sizzle这样的选择器库。没有重新发明轮子的意义。

+0

谢谢,我忘了提,我这是为了我个人的项目,我试图尽可能保持轻量级。我可能不得不通过Sizzles源代码看看,但我完全忘了它存在。谢谢! – 2010-10-04 23:23:13

-1

为广泛选择的可预测的支持与灒(或jQuery的它使用灒)去

否则,你可以使用代码片段来自: Creating a querySelector for IE that runs at “native speed” - Ajaxian

if (!document.querySelector) 
    document.querySelector = function(selector) { 
     var head = document.documentElement.firstChild; 
     var styleTag = document.createElement("STYLE"); 
     head.appendChild(styleTag); 
     document.__qsResult = []; 

     styleTag.styleSheet.cssText = selector + "{x:expression(document.__qsResult.push(this))}"; 
     window.scrollBy(0, 0); 
     head.removeChild(styleTag); 

     var result = []; 
     for (var i in document.__qsResult) { 
      result.push(document.__qsResult[i]); 
     } 
     return result; 
    } 
+0

这段代码不会起作用Bob,我已经在IE7,IE7 IEtester和现代浏览器中测试了它,当'document.querySelector = function ...'重命名为'document.customQuerySelector = function ...'时。具体来说:'styleTag.styleSheet'变成未定义的。 – 2014-07-04 09:58:05

相关问题