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
找不到正确的。
文档是不正确还是我遗漏了什么?