在jQuery中将子选择器与上下文节点一起使用的新方法是什么?

Fra*_*ila 11 javascript jquery jquery-selectors

子选择器jQuery文档中,我看到了这个注释:

注意:$("> elem", context)选择器将在以后的版本中弃用.因此不鼓励使用其替代选择器.

我一直使用这种模式,通常是这样的:

$nodes.find('> children[something=morecomplicated] > somethingelse');
Run Code Online (Sandbox Code Playgroud)

但是,我不明白他们所指的"替代选择者"是什么.编写遍历上下文节点的直接子节点的选择器的正确方法是什么? 作为奖励,任何人都可以解释为什么这是折旧的?每个人都给予的所有替代品看起来都非常难看.

这里有一些事情,工作:

// does not guarantee that '.child' is an immediate child
$nodes.find('.child > .grandchild');

// this will return empty array in recent jQuery
// and will return full list of children in older jQuery
$nodes.children('.child > .grandchild');

// Anything like this which forces you to split up the selector.
// This is ugly and inconsistent with usual selector ease-of-use,
// and is a non-trivial conversion for long or complex selectors.
$nodes.children('.child').children('.grandchild');
// After all, no one would ever recommend
$nodes.find('.this').children('.that');
// instead of
$nodes.find('.this > .that');
Run Code Online (Sandbox Code Playgroud)

Dan*_*Dan 14

他们说的原因是:

注意:$("> elem", context)选择器将在以后的版本中弃用.因此不鼓励使用其替代选择器.

是由于逗号后跟选择器中的上下文.例如$("> elem"),没关系,$("> elem", context)将被弃用.

$("> elem", context)是一样的$(context + "> elem").

获得子孙的正确方法是

$("elem").children('.child').children('.grandchild');
Run Code Online (Sandbox Code Playgroud)

要么

context.children('.child').children('.grandchild');
Run Code Online (Sandbox Code Playgroud)

要么

context.find('> .child > .grandchild');
Run Code Online (Sandbox Code Playgroud)