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.

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

更多相关文章

  1. Javascript XML DOM将属性设置为特定元素
  2. jquery.fullCalendar官方文档翻译(一款小巧好用的日程管理日历,
  3. 获取JavaScript数组元素的最大长度
  4. 获取html DOM元素内容的边框
  5. 是否有办法阻止contenteditable的插入符号出现在IE10的元素上?
  6. 获取拆分字符串数组的最后一个元素
  7. CSS3(jQUery?)当它悬停时隐藏元素“a”,这样就可以显示元素“b”
  8. 停止鼠标用javascript双击某些元素
  9. 在量角器中检索子元素的数组

随机推荐

  1. Android接收短信
  2. Android 之 对话框总结
  3. Android Layout 布局属性全解
  4. Android v7 Toolbar的使用
  5. Android进程启动流程(App启动)
  6. Androidの应用源码下载地址
  7. Android判断应用是否存在
  8. Android之文件&XML
  9. Android Media Framework 总纲
  10. Android Component 简介