首页 > 语言 > JavaScript > 正文

jQuery选择器源码解读(八):addCombinator函数

2024-05-06 14:43:53
字体:
来源:转载
供稿:网友

function addCombinator(matcher, combinator, base)

1、源码
代码如下:
function addCombinator(matcher, combinator, base) {
 var dir = combinator.dir, checkNonElements = base
   && dir === "parentNode", doneName = done++;

 return combinator.first ?
 // Check against closest ancestor/preceding element
 function(elem, context, xml) {
  while ((elem = elem[dir])) {
   if (elem.nodeType === 1 || checkNonElements) {
    return matcher(elem, context, xml);
   }
  }
 } :

 // Check against all ancestor/preceding elements
 function(elem, context, xml) {
  var data, cache, outerCache, dirkey = dirruns + " " + doneName;

  // We can't set arbitrary data on XML nodes, so they don't
  // benefit from dir caching
  if (xml) {
   while ((elem = elem[dir])) {
    if (elem.nodeType === 1 || checkNonElements) {
     if (matcher(elem, context, xml)) {
      return true;
     }
    }
   }
  } else {
   while ((elem = elem[dir])) {
    if (elem.nodeType === 1 || checkNonElements) {
     outerCache = elem[expando] || (elem[expando] = {});
     if ((cache = outerCache[dir])
       && cache[0] === dirkey) {
      if ((data = cache[1]) === true
        || data === cachedruns) {
       return data === true;
      }
     } else {
      cache = outerCache[dir] = [ dirkey ];
      cache[1] = matcher(elem, context, xml)
        || cachedruns;
      if (cache[1] === true) {
       return true;
      }
     }
    }
   }
  }
 };
}

2、功能

生成关系选择器的执行函数。

3、参数

matcher——位置关系前连续的过滤选择器匹配函数数组,该函数用于匹配通过位置关系获得的节点是否符合选择器要求。在实际执行过程中,该函数可能是关系选择器前已生成的elementMatcher(matchers)。例如:div.map>span,在Sizzle编译遇到>时,会将div.map的编译函数作为第一个参数调用addCombinator函数,用以检查获取的span父节点是否满足div.map这两个条件。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选