如何使用 jQuery 在容器内进行选择?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1409280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:23:12  来源:igfitidea点击:

How to select within a container with jQuery?

jquerydom

提问by omg

<div id="container1">
<span>...</span>
</div>
<div id="container2">
<span>...</span>
</div>

Say if I have get the jQuery object $('container1'),how to find the <span>in it?

假设我已经获得了 jQuery 对象 $('container1'),如何在其中找到<span>

回答by peirix

I know you have accepted an answer, I'd just like to add another way of doing this:

我知道你已经接受了一个答案,我只想添加另一种方法:

$("span", $container1); //This will start in your variable $container1
                          and then look for all spans

I haven't tested performance on these yet, so I don't know which is better. Just thought I'd let you know you have more options (:

我还没有测试这些性能,所以我不知道哪个更好。只是想我会让你知道你有更多的选择(:

回答by CMS

Just select the descendantspan:

只需选择后代跨度:

$('#container1 span');

Note that this will select any span inside #container1, even if is not a direct descendant.

请注意,这将选择 #container1 内的任何跨度,即使不是直接后代。

If you want to select only direct descendants, use the parent > childselector:

如果只想选择直接后代,请使用parent > child选择器:

$('#container1 > span');

If you have only an object reference you could:

如果您只有一个对象引用,您可以:

$container1.find('span');

Or

或者

$container1.children('span');

回答by pixeline

There are a lot of ways to do that. According to your comment at CMS answer:

有很多方法可以做到这一点。根据您在 CMS 上的评论回答:

$('#container1').find('span:first');

and

$('#container1 span:first');

on top of CMS's other suggestions.

在 CMS 的其他建议之上。

回答by PatrikAkerstrand

Use find( expr ). Example:

使用find( expr )。例子:

$("p").find("span").css('color','red');