jQuery选择器,用于查找与选择器匹配的给定元素之后的第一个元素

时间:2021-10-09 21:58:27

Let's say I have this HTML:

假设我有这个HTML:

 <textarea>blah</textarea>
 <br>
 <div class="select_this">hello!</div>

How can I select the DIV with class "select_this" when I already have the textarea identified? I don't want to use a class selector on the entire document because I'm working with a large document and class lookups are slow in older browsers.

当我已经识别出textarea时,如何选择带有“select_this”类的DIV?我不想在整个文档上使用类选择器,因为我正在使用大型文档,并且在旧版浏览器中类查找速度很慢。

jQuery .next() doesn't seem to do the trick, closest() only looks up the DOM tree, and .nextUntil() qualifies on everything I need except for the "select_this" div. Any other options out there?

jQuery .next()似乎没有这个技巧,nearest()只查找DOM树,而.nextUntil()限定了我需要的一切,除了“select_this”div。还有其他选择吗?

2 个解决方案

#1


19  

There are two ways to do it.

有两种方法可以做到这一点。

Use this if you only have a few siblings:

如果您只有几个兄弟姐妹,请使用此选项:

$('textarea').nextAll('div.select_this').first();

The downside of this is that it test every subsequent element to see if it matches the selector, even after it's found the first one. Use this if you have many, many siblings, to save on evaluation:

这样做的缺点是它会测试每个后续元素,看它是否与选择器匹配,即使它找到了第一个元素。如果你有许多兄弟姐妹,请使用它来保存评估:

$('textarea').nextUntil('div.select_this').andSelf().last().next();

Note also that it's better to use the first and last methods, rather than their corresponding selectors (:first, :last), because browsers don't natively understand the selectors, which slows the expression down considerably.

还要注意,最好使用第一个和最后一个方法,而不是它们相应的选择器(:first,:last),因为浏览器本身并不理解选择器,这会大大降低表达式。

Edited to incorporate andSelf per comment below.

编辑将以下评论纳入自评。

#2


3  

You want nextAll:

你想要nextAll:

jQuery(yourTextarea).nextAll('.select_this:first');

#1


19  

There are two ways to do it.

有两种方法可以做到这一点。

Use this if you only have a few siblings:

如果您只有几个兄弟姐妹,请使用此选项:

$('textarea').nextAll('div.select_this').first();

The downside of this is that it test every subsequent element to see if it matches the selector, even after it's found the first one. Use this if you have many, many siblings, to save on evaluation:

这样做的缺点是它会测试每个后续元素,看它是否与选择器匹配,即使它找到了第一个元素。如果你有许多兄弟姐妹,请使用它来保存评估:

$('textarea').nextUntil('div.select_this').andSelf().last().next();

Note also that it's better to use the first and last methods, rather than their corresponding selectors (:first, :last), because browsers don't natively understand the selectors, which slows the expression down considerably.

还要注意,最好使用第一个和最后一个方法,而不是它们相应的选择器(:first,:last),因为浏览器本身并不理解选择器,这会大大降低表达式。

Edited to incorporate andSelf per comment below.

编辑将以下评论纳入自评。

#2


3  

You want nextAll:

你想要nextAll:

jQuery(yourTextarea).nextAll('.select_this:first');