jQuery选择器用于查找匹配选择器的给定元素之后的第一个元素 [英] jQuery selector for finding the first element after a given element that matches a selector

查看:90
本文介绍了jQuery选择器用于查找匹配选择器的给定元素之后的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样的HTML:

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

当我已经识别了textarea时,如何选择类为select_this的DIV?我不希望在整个文档上使用类选择器,因为我正在处理大型文档,并且在较旧的浏览器中类查找速度较慢。



jQuery .next ()似乎并没有做到这一点,nearest()只查找DOM树,而.nextUntil()符合除select_thisdiv之外的所有需求。还有其他的选择吗?

解决方案



如果你只有几个兄弟姐妹,可以使用它:

  $('textarea')。nextAll('div。 。select_this')第一(); 

它的缺点是它会测试每个后续元素,看它是否与选择器匹配,即使在它被发现是第一个。如果您有很多很多兄弟姐妹,请在评估时节省时间:

  $('textarea ').nextUntil(' div.select_this')andSelf()最后()下()。; 

请注意,最好使用 first last 方法,而不是其对应的选择器( :first :上次 ),因为浏览器本身并不理解选择器,这大大降低了表达式的速度。



编辑合并 andSelf 每个评论下面。


Let's say I have this 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.

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?

解决方案

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.

Edited to incorporate andSelf per comment below.

这篇关于jQuery选择器用于查找匹配选择器的给定元素之后的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆