使用jquery .find()来获取子项

时间:2020-12-18 19:42:33

I have the following markup:

我有以下标记:

<div id="items">
   <div class="item">
     <div class="item_box" id="id_1">
       <div class="one" id="one"></div>
     </div>
    </div>
   <div class="item">
     <div class="item_box" id="id_2">
       <div class="one" id="two"></div>
     </div>
    </div>
   <div class="item">
     <div class="item_box" id="id_3">
       <div class="one" id="three"></div>
     </div>
    </div>
 </div>

Basically, I want to be able to loop through and get the id value in the item_box class.

基本上,我希望能够遍历并获取item_box类中的id值。

Here's the code I'm trying to use:

这是我正在尝试使用的代码:

$('#items').find(/[id_]/).each(
      function(){
         alert($(this).attr('id'));
      });

This doesn't work though... I've tried using .children, however that won't go as deep as these are nested.

这虽然不起作用......我尝试过使用.children,但是这些不会像嵌套那样深。

Any ideas?

Thanks!

3 个解决方案

#1


2  

$('#items').find('.item_box').each(function(){
    alert($(this).attr('id'));
});

#2


0  

You were very close. Here's your code, modified to search for children of #items which have an id that starts with id_

你非常接近。这是你的代码,经过修改以搜索#items的子代,这些代码的id以id_开头

$('#items *[id^=id_]').each(function(){
    alert($(this).attr('id'));
});

#3


0  

  1. Search by Class 'item_box'
  2. 按类'item_box'搜索

  3. iterate them to collect ids
  4. 迭代它们来收集ID

$(function(){

    var child = $('#items').find('div.item_box');

    var idArray = new Array();

    if(child.length){

        $.each(child,function(i,entry){

            idArray.push($(this).attr('id'));

        });

    }

    console.log(idArray);

});​

Fiddle Assistance : http://jsfiddle.net/FFp4B/

小提琴援助:http://jsfiddle.net/FFp4B/

#1


2  

$('#items').find('.item_box').each(function(){
    alert($(this).attr('id'));
});

#2


0  

You were very close. Here's your code, modified to search for children of #items which have an id that starts with id_

你非常接近。这是你的代码,经过修改以搜索#items的子代,这些代码的id以id_开头

$('#items *[id^=id_]').each(function(){
    alert($(this).attr('id'));
});

#3


0  

  1. Search by Class 'item_box'
  2. 按类'item_box'搜索

  3. iterate them to collect ids
  4. 迭代它们来收集ID

$(function(){

    var child = $('#items').find('div.item_box');

    var idArray = new Array();

    if(child.length){

        $.each(child,function(i,entry){

            idArray.push($(this).attr('id'));

        });

    }

    console.log(idArray);

});​

Fiddle Assistance : http://jsfiddle.net/FFp4B/

小提琴援助:http://jsfiddle.net/FFp4B/