Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
132 views
in Technique[技术] by (71.8m points)

javascript - What is the new proper way to use a child selector with a context node in jQuery?

In the jQuery documentation for the child selector I saw this note:

Note: The $("> elem", context) selector will be deprecated in a future release. Its usage is thus discouraged in lieu of using alternative selectors.

I use this pattern all the time, usually like this:

$nodes.find('> children[something=morecomplicated] > somethingelse');

However, I don't understand what the "alternative selectors" they refer to could be. What is the right way to write a selector which traverses the immediate children of a context node? As a bonus, can anyone explain why this is depreciated? All the alternatives everyone is giving seem amazingly ugly.

Here are some things that don't work:

// 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');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason they are saying:

Note: The $("> elem", context) selector will be deprecated in a future release. Its usage is thus discouraged in lieu of using alternative selectors.

Is due to the comma followed by the context in the selector. E.g. $("> elem") is fine however, $("> elem", context) will be deprecated.

$("> elem", context) is the same as $(context + "> elem").

A correct way of obtaining children and grandchildren is

$("elem").children('.child').children('.grandchild');

or

context.children('.child').children('.grandchild');

or

context.find('> .child > .grandchild');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...