gpt4 book ai didi

javascript - 这个 jQuery 选择是什么意思?为什么我们在 filter() 中使用 "this"?

转载 作者:行者123 更新时间:2023-11-30 08:27:56 25 4
gpt4 key购买 nike

我以这种方式使用 filter() 但它不起作用:

$("p").filter(function(){  
return $("span").length == 2;}).css("background-color", "yellow");});

如果我在 "span" 旁边添加 this 问题就解决了。我不知道用 , 分隔成一个 $ 的 2 个元素的原因是什么,它有什么含义。实际上,到目前为止我还没有看到 2 个参数一起进入 $ 。请告诉我什么时候以及为什么我必须在这个例子中使用 this

$("p").filter(function(){  
return $("span", this).length == 2;}).css("background-color", "yellow");});

最佳答案

第二个参数是上下文,这意味着您的选择器将尝试在上下文中找到 spanthis 指的是 p在你的情况下本身,所以所有匹配的跨度都将在 p 上下文中。

从代码看来,您在整个文档(全局上下文)中有超过 2 个跨度,所以当您使用时:

$("span").length 在全局上下文中大于 2。

但是在 p 的上下文中,当使用 $("span", this) 时,您发现了 2 个子 span。

关于javascript - 这个 jQuery 选择是什么意思?为什么我们在 filter() 中使用 "this"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42242745/

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