在jQuery中将子选择器与上下文节点一起使用的新方法是什么? [英] What is the new proper way to use a child selector with a context node in jQuery?

查看:126
本文介绍了在jQuery中将子选择器与上下文节点一起使用的新方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


注意: $(> elem,上下文)选择器将被弃用未来的版本。因此不鼓励使用替代选择器。

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');


推荐答案

他们说的原因是:


注意: $(> elem,上下文)选择器将来会被弃用发布。因此不鼓励使用其替代选择器。

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

由于逗号后跟选择器中的上下文。例如。 $(> elem)但是, $(> elem,上下文)将是弃用。

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 +> elem)。

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

获得子女和孙子女的正确方法是

A correct way of obtaining children and grandchildren is

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

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

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

这篇关于在jQuery中将子选择器与上下文节点一起使用的新方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆