javascript jQuery 获取特定类的第二个或 x div

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

jQuery Get the second or x div with certain class

javascriptjqueryhtml

提问by kr1zmo

This should be simple, but I can't figure it out

这应该很简单,但我想不通

For example, lets assume the class .contentdiv is what were searching for.

例如,假设类 .contentdiv 是正在搜索的内容。

I want to obtain (or select) the second or (x amount) .contentdiv in a document then get the html of that div.

我想获取(或选择)文档中的第二个或(x 数量).contentdiv,然后获取该 div 的 html。

x being the div i want to select so pretend x is 1,2 or 3 or any number

x 是我想要选择的 div 所以假装 x 是 1,2 或 3 或任何数字

jQuery('#slider').filter('.contentdiv').match(x).html();

回答by Pointy

There are a couple of ways, but:

有几种方法,但是:

$('#slider').filter('contentdiv').eq(x).html();

also

$('#slider').filter('.contentdiv:eq(' + x + ')').html();

but that's messier (in my opinion).

但这更麻烦(在我看来)。

edit— thanks @patrick: the initial selector is selecting a single element (of necessity, because "id" values have to be unique). Perhaps you meant $('#slider div.contentdiv')which would get all the <div>elements under` the "slider" container.

编辑——感谢@patrick:初始选择器正在选择单个元素(这是必要的,因为“id”值必须是唯一的)。也许您的意思$('#slider div.contentdiv')是将所有<div>元素放在“滑块”容器下。

And another good comment further clarifies that the indexing of .eq()and the ":eq()" selector thingy is zero-based.

另一个很好的评论进一步澄清.eq()了“:eq()”选择器的索引 是从零开始的。

回答by user113716

If .contentdivelements are located inside the #sliderelement then you need .find()instead of .filter().

如果.contentdiv元素位于元素内部,#slider那么您需要.find()而不是.filter().

Any of these would work for you:

这些中的任何一个都适合你:

jQuery('#slider').find('.contentdiv').eq(1);
jQuery('#slider .contentdiv').eq(1);
jQuery('#slider .contentdiv:eq(1)');

replacing 1with whatever number (or variable) you want, and ending with .html().

替换1为您想要的任何数字(或变量),并以.html().

回答by Joe

Hm..

嗯..

$('#slider').find('.contentdiv:eq(x)').html();

$('#slider').find('.contentdiv:eq(x)').html();

edit...

编辑...

$('#slider').find('.contentdiv:eq(' + x + ')').html();

$('#slider').find('.contentdiv:eq(' + x + ')').html();

回答by CharlesLeaf

Maybe the nth-childselector? For example, #slider .contentdiv:nth-child(2)?

也许是nth-child选择器?例如,#slider .contentdiv:nth-child(2)?