gpt4 book ai didi

jQuery .closest 默认上下文

转载 作者:行者123 更新时间:2023-12-03 22:18:46 26 4
gpt4 key购买 nike

jquery closest 的文档说明如下:

.closest( selector [, context ] )
...
context
Type: Element
A DOM element within which a matching element may be found. If no context is passed in then the context of the jQuery set will be used instead.

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

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 正确地未找到。

文档是否不正确或者我遗漏了什么?

最佳答案

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

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等于 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

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

我怀疑这就是我们的意图,而且这似乎是一件奇怪的事情,而且它肯定没有按照文档所说的那样做。

关于jQuery .closest 默认上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34580013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com