Jam*_*gne 11 jquery jquery-context
jquery的文档说明closest如下:
.closest(selector [,context])
...
context
类型:Element
可以在其中找到匹配元素的DOM元素.如果没有传递上下文,那么将使用jQuery集的上下文.
据我了解,粗体文本意味着这两个陈述应该是等价的:
set.closest("a");
set.closest("a", set.context);
Run Code Online (Sandbox Code Playgroud)
哪些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");Run Code Online (Sandbox Code Playgroud)
#outer{
width: 100px;
height: 100px;
border: 1px solid black;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
如您所见,当没有显式设置上下文时,似乎没有使用集合的上下文,因为#outer找到了元素closest.显式设置时,#outer未正确找到.
文档是不正确的还是我遗漏了什么?
这显然是一个错误,而不是它的工作方式.
来源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);
}
Run Code Online (Sandbox Code Playgroud)
值得注意的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
Run Code Online (Sandbox Code Playgroud)
如果传入的选择器与该正则表达式不匹配,则不会使用任何上下文,pos它将等于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
Run Code Online (Sandbox Code Playgroud)
那么如果你添加一个伪选择器,它会突然使用上下文?
我怀疑这是有意的,这似乎是一件奇怪的事情,它肯定不会做文档所说的应该做的事情.