再谈querySelector和querySelectorAll
先按W3C的規(guī)范來說這兩個(gè)方法應(yīng)該返回的內(nèi)容吧:
querySelector:
return the first matching Element node within the node’s subtrees. If there is no such node, the method must return null.(返回指定元素節(jié)點(diǎn)的子樹中匹配selector的集合中的第一個(gè),如果沒有匹配,返回null)
querySelectorAll:
return a NodeList containing all of the matching Element nodes within the node’s subtrees, in document order. If there are no such nodes, the method must return an empty NodeList. (返回指定元素節(jié)點(diǎn)的子樹中匹配selector的節(jié)點(diǎn)集合,采用的是深度優(yōu)先預(yù)查找;如果沒有匹配的,這個(gè)方法返回空集合)
使用方法:
var element = baseElement.querySelector(selectors); var elementList = baseElement.querySelectorAll(selectors);?
這在BaseElement 為document的時(shí)候,沒有什么問題,各瀏覽器的實(shí)現(xiàn)基本一致;但是,當(dāng)BaseElement 為一個(gè)普通的dom Node的時(shí)候(支持這兩個(gè)方法的dom Node),瀏覽器的實(shí)現(xiàn)就有點(diǎn)奇怪了,舉個(gè)例子:
按照W3C的來理解,這個(gè)例子應(yīng)該返回:element:null;elementList:[];因?yàn)樽鳛閎aseElement的 testElement里面根本沒有符合selectors的匹配子節(jié)點(diǎn);但瀏覽器卻好像無視了baseElement,只在乎selectors,也就是說此時(shí)baseElement近乎document;這和我們的預(yù)期結(jié)果不合,也許隨著瀏覽器的不斷升級(jí),這個(gè)問題會(huì)得到統(tǒng)一口徑!
人的智慧總是無窮的,Andrew Dupont發(fā)明了一種方法暫時(shí)修正了這個(gè)怪問題,就是在selectors前面指定baseElement的id,限制匹配的范圍;這個(gè)方法被廣泛的應(yīng)用在各大流行框架中;
Jquery的實(shí)現(xiàn):
nid = old || id,try { if ( !relativeHierarchySelector || hasParent ) {return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );} } catch(pseudoError) {}
finally {if ( !old ) {oldContext.removeAttribute( "id" );} }
先不看這點(diǎn)代碼中其他的地方,只看他如何實(shí)現(xiàn)這個(gè)方法的;這點(diǎn)代碼是JQuery1.6的片段;當(dāng)baseElement沒有ID的時(shí)候,給他設(shè)置一個(gè)id = "__sizzle__”,然后再使用的時(shí)候加在selectors的前面,做到范圍限制;context.querySelectorAll( "[id='" + nid + "'] " + query ;最后,因?yàn)檫@個(gè)ID本身不是baseElement應(yīng)該有的,所以,還需要移除:oldContext.removeAttribute( "id" );
,Mootools的實(shí)現(xiàn):
Mootools和Jquery類似:只不過slickid = 'slickid__';其實(shí)意義是一樣的;
方法兼容性:FF3.5+/IE8+/Chrome 1+/opera 10+/Safari 3.2+;
IE 8 :不支持baseElement為object;
非常感謝大牛JK的回復(fù),提供了另外一種方法。
轉(zhuǎn)載于:https://www.cnblogs.com/zorroLiu/archive/2011/05/13/2045322.html
總結(jié)
以上是生活随笔為你收集整理的再谈querySelector和querySelectorAll的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Django使用心得(四)
- 下一篇: svn +nginx