如何通过选择器仅选择缓存的jQuery上下文的直接子体

How to select only direct descendants of cached jQuery context by selector

本文关键字:上下文 jQuery 选择器 选择 缓存 何通过      更新时间:2023-09-26

我有一个缓存的jQuery对象。。。

$main = $('#main');

我想选择所有标签名为"span"的直接子项。。。

$('span', $main); // this selects all descendants, not all direct children
$(' > span', $main); // this does not work at all

我知道我可以做$('#main > span'),它工作得很好,但我想重用缓存的选择器。

如何从缓存选择器中仅选择直接子项?

jQuery有一个子方法:
$main.children('span')

使用类似$main.children("span")的jQuery children(selector)函数获取更多信息:https://api.jquery.com/children/