日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

再谈querySelector和querySelectorAll

發(fā)布時間:2025/7/14 58 豆豆
生活随笔 收集整理的這篇文章主要介紹了 再谈querySelector和querySelectorAll 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

先按W3C的規(guī)范來說這兩個方法應(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é)點的子樹中匹配selector的集合中的第一個,如果沒有匹配,返回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é)點的子樹中匹配selector的節(jié)點集合,采用的是深度優(yōu)先預(yù)查找;如果沒有匹配的,這個方法返回空集合)

使用方法:

var element = baseElement.querySelector(selectors); var elementList = baseElement.querySelectorAll(selectors);

?
這在BaseElement 為document的時候,沒有什么問題,各瀏覽器的實現(xiàn)基本一致;但是,當BaseElement 為一個普通的dom Node的時候(支持這兩個方法的dom Node),瀏覽器的實現(xiàn)就有點奇怪了,舉個例子:

<div class="test" id="testId"> <p><span>Test</span></p> </div> <script type="text/javascript"> var testElement= document.getElementById('testId'); var element = testElement.querySelector('.test span'); var elementList = document.querySelectorAll('.test span'); console.log(element); // <span>Test</span> console.log(elementList); // 1 </script>


按照W3C的來理解,這個例子應(yīng)該返回:element:null;elementList:[];因為作為baseElement的 testElement里面根本沒有符合selectors的匹配子節(jié)點;但瀏覽器卻好像無視了baseElement,只在乎selectors,也就是說此時baseElement近乎document;這和我們的預(yù)期結(jié)果不合,也許隨著瀏覽器的不斷升級,這個問題會得到統(tǒng)一口徑!
人的智慧總是無窮的,Andrew Dupont發(fā)明了一種方法暫時修正了這個怪問題,就是在selectors前面指定baseElement的id,限制匹配的范圍;這個方法被廣泛的應(yīng)用在各大流行框架中;
Jquery的實現(xiàn):

var oldContext = context,old = context.getAttribute( "id" ),
nid = old || id,try { if ( !relativeHierarchySelector || hasParent ) {return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );} } catch(pseudoError) {}
finally {if ( !old ) {oldContext.removeAttribute( "id" );} }

先不看這點代碼中其他的地方,只看他如何實現(xiàn)這個方法的;這點代碼是JQuery1.6的片段;當baseElement沒有ID的時候,給他設(shè)置一個id = "__sizzle__”,然后再使用的時候加在selectors的前面,做到范圍限制;context.querySelectorAll( "[id='" + nid + "'] " + query ;最后,因為這個ID本身不是baseElement應(yīng)該有的,所以,還需要移除:oldContext.removeAttribute( "id" );
,Mootools的實現(xiàn):

var currentId = _context.getAttribute('id'), slickid = 'slickid__';_context.setAttribute('id', slickid);_expression = '#' + slickid + ' ' + _expression;context = _context.parentNode;

Mootools和Jquery類似:只不過slickid = 'slickid__';其實意義是一樣的;

方法兼容性: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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。