您好,欢迎访问一九零五行业门户网

再谈querySelector和querySelectorAll的区别与联系_javascript技巧

先按w3c的规范来说这两个方法应该返回的内容吧:
queryselector:
return the first matching element node within the node's subtrees. if there is no such node, the method must return null.(返回指定元素节点的子树中匹配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. (返回指定元素节点的子树中匹配selector的节点集合,采用的是深度优先预查找;如果没有匹配的,这个方法返回空集合)
使用方法:
复制代码 代码如下:
var element = baseelement.queryselector(selectors);
var elementlist = baseelement.queryselectorall(selectors);
这在baseelement 为document的时候,没有什么问题,各浏览器的实现基本一致;但是,当baseelement 为一个普通的dom node的时候(支持这两个方法的dom node),浏览器的实现就有点奇怪了,举个例子:
复制代码 代码如下:
test
按照w3c的来理解,这个例子应该返回:element:null;elementlist:[];因为作为baseelement的 testelement里面根本没有符合selectors的匹配子节点;但浏览器却好像无视了baseelement,只在乎selectors,也就是说此时baseelement近乎document;这和我们的预期结果不合,也许随着浏览器的不断升级,这个问题会得到统一口径!
人的智慧总是无穷的,andrew dupont发明了一种方法暂时修正了这个怪问题,就是在selectors前面指定baseelement的id,限制匹配的范围;这个方法被广泛的应用在各大流行框架中;
jquery的实现:
复制代码 代码如下:
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 );}
}
先不看这点代码中其他的地方,只看他如何实现这个方法的;这点代码是jquery1.6的片段;当baseelement没有id的时候,给他设置一个id = __sizzle__”,然后再使用的时候加在selectors的前面,做到范围限制;context.queryselectorall( [id=' + nid + '] + query ;最后,因为这个id本身不是baseelement应该有的,所以,还需要移除:oldcontext.removeattribute( id );
,mootools的实现:
复制代码 代码如下:
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的回复,提供了另外一种方法。
其它类似信息

推荐信息