【发布时间】:2016-04-07 09:47:54
【问题描述】:
jquery 的 closest 的文档说明如下:
.closest( 选择器 [, 上下文 ] )
...
上下文
类型:元素
一个 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 正确找不到。
是文档不正确还是我遗漏了什么?
【问题讨论】:
-
我猜文档是错误的。如果没有指定上下文,它看起来不像使用 jQuery 集的上下文。
-
你为什么喜欢
var set = $("#el", context);?根据阅读我得到的内容的文档,closest()尝试将selector表达式匹配到祖先链上,直到找到匹配项。现在第二个参数closest()方法只是给它一个限制,直到它会继续寻找匹配。如果没有第二个参数,它将由 Jquery 决定body可能是最后一个父级。 -
所以你的代码看起来不像是反对 Jquery 文档的正确示例。
-
这有点令人困惑,因为 jQuery 的
closest()并不总是使用上下文,它使用正则表达式来确定是否需要上下文,例如/^[\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,所以只需将其更改为set.closest("#outer:first")使它使用上下文,不再匹配元素,而$('#el').closest("#outer:first")仍然像它应该的那样匹配元素。 -
我更喜欢使用
parents( selector )作为父元素,在您的代码中只需使用 id 选择器
标签: jquery jquery-context