jquery,按类查找下一个元素

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

jquery, find next element by class

jqueryclasselementnext

提问by Alex

How can i find the next element by class.

如何按类找到下一个元素。

i tried with $(obj).next('.class');but this returns classes only in $(obj)parent. I need to take the next element anywhere throughout the code by class name. Because my code looks like

我尝试过,$(obj).next('.class');但这仅在$(obj)父级中返回类。我需要通过类名在整个代码中的任何地方获取下一个元素。因为我的代码看起来像

<table>
<tr><td><div class="class">First</div></td></tr>
<tr><td><div class="class">Second</div></td></tr>
</table>

Is this possible?

这可能吗?

回答by Nick Craver

In this case you need to go up to the <tr>thenuse .next(), like this:

在这种情况下,您需要转到<tr>thenuse .next(),如下所示:

$(obj).closest('tr').next().find('.class');

Or if there may be rows in-between without the .classinside, you can use .nextAll(), like this:

或者,如果中间可能有没有.class内部的行,您可以使用.nextAll(),如下所示:

$(obj).closest('tr').nextAll(':has(.class):first').find('.class');

回答by plavozont

To find the next element with the same class:

要查找具有相同类的下一个元素:

$(".class").eq( $(".class").index( $(element) ) + 1 )

回答by Morteza Manavi

You cannot use next() in this scenario, if you look at the documentationit says:
Next() Get theimmediately following sibling of each elementin the set of matched elements. If a selector is provided, it retrieves the next sibling that matches the selector.

so if the second DIV was in the same TD then you could code:

在这种情况下您不能使用 next() ,如果您查看文档,它说:
Next() 获取匹配元素集中每个元素紧随其后的同级。如果提供了选择器,它将检索与选择器匹配的下一个同级。

所以如果第二个 DIV 在同一个 TD 中,那么你可以编码:


// Won't work in your case
$(obj).next().filter('.class');



但既然不是,我看不到使用 next() 的意义。您可以改为编码:

$(obj).parents('table').find('.class')