14

我一直在尋找除Sizzle以外的CSS選擇器功能,我遇到過this functiondocument.evaluate - 跨瀏覽器?

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?

+0

我認爲這只是Firefox,多麼令人失望。顯然,IE可以在XML文檔上做到這一點。 – Olical 2011-01-13 15:58:20

+0

o我的上帝終於找到了和iam一樣的方式:)))))))))))))) http://stackoverflow.com/questions/15310502/how-to-create-a- javascript-selector-engine – Marwan 2013-03-10 11:37:37

回答

10

我相信no stable version of IE supports document.evaluate,所以你只限於其他任何瀏覽器。這不是很慢,因爲它是XPath的本地實現。因爲它採用了原生支持的瀏覽器提供可用的時候(如document.getElementsByClassName

灒是有用的,但回落到這樣做本身時可用(IE)。它也被jQueryPrototype使用,所以它經過嚴格的測試,不會給你帶來任何麻煩。嘶嘶聲也經過了嚴格的速度測試和優化(他們有一個完整的speed test suite),這是更多的工作,你不必做。除非你正在做一些令人難以置信的對性能敏感的東西(說實話,這很可能是你的應用程序結構很差的一個指標),否則我會說jQuery,Prototype或者Sizzle本身。