11

jquery 的文档说明closest如下:

.closest( selector [, context ] )
...
context
类型:元素
可以在其中找到匹配元素的 DOM 元素。如果没有传入上下文,则将使用 jQuery 集的上下文。

据我了解,粗体文本意味着这两个语句应该是等价的:

set.closest("a");

set.closest("a", set.context);

set一些 jquery 集 在哪里。

但是,情况似乎并非如此:

var context = $("#inner")[0];
var set = $("#el", context);

// the set's context is correctly the "inner" element
set.text("context: " + set.context.id);

// if the set's context is used, this closest should match nothing, but it matches and sets the color
set.closest("#outer").css("color", "red");

// with the context explicitly set, the "outer" is not found and no background color is set
set.closest("#outer", set.context).css("background-color", "blue");
#outer{
  width: 100px;
  height: 100px;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="outer">
  <div id="inner">
    <div id="el"></div>
  </div>
</div>

如您所见,当没有明确设置上下文时,似乎没有使用该集合的上下文,因为该#outer元素是由closest. 明确设置时,#outer找不到正确的。

文档是不正确还是我遗漏了什么?

4

1 回答 1

5

这显然是一个错误,而不是它的预期工作方式。

的来源closest()

function (selectors, context) {
    var cur, 
        i = 0,
        l = this.length,
        matched = [],
        pos = rneedsContext.test(selectors) || typeof selectors !== "string" 
           ? 
           jQuery(selectors, context || this.context) 
           : 
           0;

    for (; i < l; i++) {
        for (cur = this[i]; cur && cur !== context; cur = cur.parentNode) {
            // Always skip document fragments
            if (cur.nodeType < 11 && (pos ? pos.index(cur) > -1 :

            // Don't pass non-elements to Sizzle
            cur.nodeType === 1 && jQuery.find.matchesSelector(cur, selectors))) {

                matched.push(cur);
                break;
            }
        }
    }

    return this.pushStack(matched.length > 1 ? jQuery.unique(matched) : matched);
}

值得注意的pos是定义的方式,它是要搜索最近父元素的集合,并且rneedsContext是正则表达式

/^[\x20\t\r\n\f]*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\([\x20\t\r\n\f]*((?:-\d)?\d*)[\x20\t\r\n\f]*\)|)(?=[^-]|$)/i

如果传入的选择器与该正则表达式不匹配,则不使用任何上下文,pos将 equal 0,并且该集合中的检查cur将一起被跳过,这看起来很奇怪。

快速测试显示

var reg = /^[\x20\t\r\n\f]*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\([\x20\t\r\n\f]*((?:-\d)?\d*)[\x20\t\r\n\f]*\)|)(?=[^-]|$)/i;

reg.test('#outer');       // false, no context used
reg.test('#outer:first'); // true, context used
reg.test('#outer:eq(0)'); // true, context used

所以如果你添加一个伪选择器,它会突然使用上下文?

我怀疑这是否是预期的,这似乎是一件奇怪的事情,而且它肯定不会像文档所说的那样做。

于 2016-01-03T19:44:10.010 回答