jQuery jQuery按未知路径的类选择子元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18016766/
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 20:21:58  来源:igfitidea点击:

jQuery select child element by class with unknown path

jqueryclasshtmlselectorcss-selectors

提问by Adam James

I am trying to figure out the syntax for selecting a nth-child of an element by its class, however I don't know the exact path to the element. I can't do $('parent > child > grandchild > hereIam');

我试图找出按类选择元素的第 n 个子元素的语法,但是我不知道元素的确切路径。我做不到$('parent > child > grandchild > hereIam');

So basically I need to be able to say

所以基本上我需要能够说

$('#thisElement').AllRelativesWithClass('.classToSelect')

How exactly do I do that?

我该怎么做?

回答by Casey

According to this documentation, the find method will search down through the tree of elements until it finds the element in the selector parameters. So $(parentSelector).find(childSelector)is the fastest and most efficient way to do this.

根据此文档, find 方法将向下搜索元素树,直到在选择器参数中找到该元素。所以$(parentSelector).find(childSelector)是最快和最有效的方法来做到这一点。

回答by cfs

$('#thisElement').find('.classToSelect')will find any descendents of #thisElementwith class classToSelect.

$('#thisElement').find('.classToSelect')将找到#thisElementwith 类的任何后代classToSelect

回答by Joe Meyer

This should do the trick:

这应该可以解决问题:

$('#thisElement').find('.classToSelect')

回答by Sonu Sindhu

Try this

尝试这个

$('#thisElement .classToSelect').each(function(i){
         // do stuff
});

Hope it will help

希望它会有所帮助