如何使用具有深度限制的jQuery find()? [英] How can I use jQuery find() with a depth limit?

查看:274
本文介绍了如何使用具有深度限制的jQuery find()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用jquery的"find"选择器来获取所有具有"field_container"类的div.问题是我不能深入DOM树.

I need to use jquery's "find" selector to get all divs having the class "field_container". The problem is that I can't go too deep in the DOM tree.

这是我简化的HTML结构:

Here is my simplified HTML structure:

<div id='tab_0'>

 <div id='form_content'>

  <div class='field_container'>
   <span>Div 1</span>
   <div class='field_container'>
   <span>Div 1.1</span>
   </div>
  </div>

  <div class='field_container'>
   <span>Div 2</span>
  </div>

  <div class='field_container'>
   <span>Div 3</span>
  </div>

 </div> <!-- Closing form_content div//-->

</div> <!-- Closing tab_0 div//-->

我最初引用了"tab_0" div.从它开始,我需要获取所有"field_container" div,不包括子"field_containers".

I have a initial reference to the "tab_0" div. Starting from it, I need to obtain all "field_container" divs, excluding child "field_containers".

我已经尝试过了:

$('#tab_0').children('.field_container') -> doesnt work, because the "field_container" divs arent direct children.

$('#tab_0').find('.field_container') -> doesnt work, because "Div 1.1" is also returned. I only need the first-level ones (Div1, Div2, Div3).

我无法更改我的初始引用,它必须是"tab_0".

I can't change my initial reference, it has to be "tab_0".

推荐答案

有几种解决方法.

一个比较快的是:

$('#tab_0').children('#form_content').children('.field_container')

由于它的限制,每个限制只能遍历一个级别到DOM树中.我不确定,但这应该比带有复杂选择器的find()更快(但在每种情况下都更简单).

due to it's restriction of only traversing one level into the DOM tree each. I'm not entirely sure but this should be quicker (but in every case simpler) than a find() with a complex selector.

这篇关于如何使用具有深度限制的jQuery find()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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