3.11 便捷方法
3.11.1 Sizzle.matches( expr, set )
便捷方法Sizzle.matches( expr, set )使用指定的选择器表达式expr对元素集合set进行过滤,并返回过滤结果。
该方法通过简单地调用函数Sizzle( selector, context, results, seed )来实现,调用时会将元素集合set作为参数seed传入。
相关代码如下所示:
4043 Sizzle.matches = function( expr, set ) {
4044 return Sizzle( expr, null, null, set );
4045 };
3.11.2 Sizzle.matchesSelector( node, expr )
便捷方法Sizzle.matchesSelector( node, expr )用于检查某个元素node是否匹配选择器表达式expr。
如果浏览器支持原生方法matchesSelector()、mozMatchesSelector()、webkitMatchesSelector()、msMatchesSelector()中的一种,则尝试调用原生方法检查元素与选择器表达式是否匹配;如果浏览器不支持原生方法,或者支持但是检查失败(抛出异常),则调用函数Sizzle( selector, context, results, seed ),检查其返回值的长度是否大于0,调用时会将元素node封装成数组作为参数seed传入。
相关代码如下所示:
4047 Sizzle.matchesSelector = function( node, expr ) {
4048 return Sizzle( expr, null, null, [node] ).length > 0;
4049 };
5095 (function(){
5096 var html = document.documentElement,
5097 matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
5098
5099 if ( matches ) {
5100 // Check to see if it's possible to do matchesSelector
5101 // on a disconnected node (IE 9 fails this)
5102 var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
5103 pseudoWorks = false;
5104
5105 try {
5106 // This should fail with an exception
5107 // Gecko does not error, returns false instead
5108 matches.call( document.documentElement, "[test!='']:sizzle" );
5109
5110 } catch( pseudoError ) {
5111 pseudoWorks = true;
5112 }
5113
5114 Sizzle.matchesSelector = function( node, expr ) {
5115 // Make sure that attribute selectors are quoted
5116 expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
5117
5118 if ( !Sizzle.isXML( node ) ) {
5119 try {
5120 if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
5121 var ret = matches.call( node, expr );
5122
5123 // IE 9's matchesSelector returns false on disconnected nodes
5124 if ( ret || !disconnectedMatch ||
5125 // As well, disconnected nodes are said to be in a document
5126 // fragment in IE 9, so check for that
5127 node.document && node.document.nodeType !== 11 ) {
5128 return ret;
5129 }
5130 }
5131 } catch(e) {}
5132 }
5133
5134 return Sizzle(expr, null, null, [node]).length > 0;
5135 };
5136 }
5137 })();