jQuery 在选择器内部查找

jQuery find inside selector

遍历 divs,我打算编写一个选择器来获取 uls,并为每个 uls 做一些事情。

我的 HTML(简体)看起来像这样:

<div class="foo">
    <ul>
    </ul>
    <ul>
    </ul>
    ...
</div>
<div class="foo">
    <ul>
    </ul>
    <ul>
    </ul>
    ...
</div>

...

此后:

variable=$(.foo);

当然可以, 现在我想做一些类似

的事情
for(var k=0;k<variable.length;k++){
variable[k].find('ul').doSomethingWithThese
}

但是选择器有问题。
即使我的尝试是在简化代码上进行的,例如示例中的代码,代码也比这复杂得多,
(在我的 divs 中还有很多事情要做,我正在构建一个带有 map() 函数的循环,每个 div 提取一些东西并与其他东西连接,然后在某处打印所有内容否则...)
所以请理解我不能像 $(".foo > ul") 那样,即使我可以我也想知道为什么我的其他尝试失败了。

我在过去 3 小时内尝试了所有可以想到的变体,包括: 使用 children() 而不是 find(),使用 get(0) insted of [0],在 ('ul') 之后使用 get(0) 或 [0](至少尝试获取第一个 ul),
使用 $variable, $.(variable), ($.('ul')), ($('ul')), 使用 each() 而不是 for 循环,为一切创建变量, 以上所有可能的所有组合,google,Whosebug,api.jquery.com...

比我尝试的更简单:

variable[0].children('ul')
variable[0].children('ul')[0]

和所有变体,仍然没有运气......

$('.foo ul').each(function(){
 //do whatever you want
})

jQueryeach()函数的详细使用,见here

尝试使用 .each() 函数

$('.foo').each(function(){
    var foo = $(this);
    var uls = foo.find('ul'); 
});

$('.foo ul').each(function(){
   //code...
});

$('.foo').each(function(){
    var foo = $(this);
    var uls = $('ul', foo); 
});

使用variable.each http://api.jquery.com/jquery.each/ 迭代第一个选择器返回的项目。您还需要将 .foo 更改为 '.foo'

当您将 variable[k]variable.get(k) 与 JQuery 对象一起使用时,它将为您提供基础 DOM 对象而不是 jQuery 对象。您可以使用 .each method 遍历每个元素,然后将其包装回 jQuery 对象或继续使用您的 for 循环并包装。

.每个

variable.each(function(index,element){
   var jqElement = jQuery(element); //or jQuery(this);
   var uls = jqElement.find("ul");
   uls.each(function(index2,ulElement){
      //do stuff
   });
});

For 循环

for(var k=0;k<variable.length;k++){
   var jqElement = jQuery(variable[k]);
   var uls = jqElement.find('ul');
   //etc
}

当然你可以只使用一个选择器直接得到 uls

uls = jQuery(".foo ul");
uls.each(function(index,ulElement){
   var jqUL = jQuery(this);

   //if you need a reference to the parent .foo
   var parent = jqUL.closest(".foo");

   //etc do stuff
});

jQuery returns 类似于 object 的数组,其中包含与您的选择器(如果有)匹配的 DOM 个元素。 在你的情况下 variable=$(.foo); 等同于 [<div class="foo"></div>, <div class="foo"></div> /* ... */]

因为您的 for 循环正在迭代返回数组中的 DOM 元素。您可以 re-wrap 元素作为 jQuery Object 像这样:

for(var k=0;k<variable.length;k++){
   $(variable[k]).find('ul').doSomethingWithThese
}

或使用 $.each 遍历您的 collection:

$.each(variable, function () {
  $(this).find('ul').doSomethingWithThese
});

HTML

<div class="foo">
    <ul class='myClass'>
        <li>list 1-1</li>
    </ul>
    <ul>
        <li>list 1-2</li>
    </ul>
    <ul>
        <li>list 1-3</li>
    </ul>
</div>
<div class="foo">
    <ul>
        <li>list 2-1</li>
    </ul>
    <ul class='myClass'>
        <li>list 2-2</li>
    </ul>
    <ul>
        <li>list 2-3</li>
    </ul>
</div>

JavaScript

$('.foo ul').each(function(){
    if ($(this).hasClass('myClass')){
        $(this).css('background-color', 'yellow');
    } 
})

工作示例

FIDDLE