我一直在寻找Sizzle以外的CSS选择器功能,并且遇到this function。
function SparkEn(xpath,root) {
xpath = xpath
.replace(/((^|\|)\s*)([^/|\s]+)/g,'$2.//$3')
.replace(/\.([\w-]+)(?!([^\]]*]))/g, '[@class="$1" or @class$=" $1" or @class^="$1 " or @class~=" $1 "]')
.replace(/#([\w-]+)/g, '[@id="$1"]')
.replace(/\/\[/g,'/*[');
str = '(@\\w+|"[^"]*"|\'[^\']*\')';
xpath = xpath
.replace(new RegExp(str+'\\s*~=\\s*'+str,'g'), 'contains($1,$2)')
.replace(new RegExp(str+'\\s*\\^=\\s*'+str,'g'), 'starts-with($1,$2)')
.replace(new RegExp(str+'\\s*\\$=\\s*'+str,'g'), 'substring($1,string-length($1)-string-length($2)+1)=$2');
var got = document.evaluate(xpath, root||document, null, 5, null);
var result=[];
while (next = got.iterateNext())
result.push(next);
return result;
}
我只是觉得这太好了而不能成立,这是仅Firefox功能(xpath?)还是速度慢?基本上我为什么要在这上面使用Sizzle?
最佳答案
我相信no stable version of IE supports document.evaluate
,因此您只能使用其他浏览器。这不是慢,因为它是XPath的本机实现。
Sizzle之所以有用,是因为它使用了可用的本机支持浏览器(例如document.getElementsByClassName),但是在不可用(IE)时会自行回退。 jQuery和Prototype也使用它,因此它经过了严格的测试,并且不会给您带来麻烦。 Sizzle还经过了严格的速度测试和优化(它们具有完整的speed test suite),这是您不必要做的更多工作。
我想说的是使用jQuery,Prototype或仅使用Sizzle,除非您正在做一些令人难以置信的对性能敏感的事情(老实说,这可能表明您的应用程序结构不佳)。
关于javascript - document.evaluate-跨浏览器?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4681968/