2011-02-11 155 views
7

我无法获得每个子元素的正确格式化文本,无论是作为数组还是作为文本。 。从jQuery获取儿童元素的.text()

我曾试图

变种名称=的jQuery( “childOne”)文本(); var number = jQuery(“。childTwo”)。text();

但它加入名称和编号中的所有名称/编号文本。

HTML是:

<span class="parent"><span class="childOne">David</span><span class="childTwo">541</span></span> 
<span class="parent"><span class="childOne">Gruce</span><span class="childTwo">162</span></span> 
<span class="parent"><span class="childOne">Proman</span><span class="childTwo">743</span></span> 

,我需要多暗淡阵列生成输出,使每个儿童element's文本可适当想通了。

首选输出可以是数组或任何形式。

Array 
(
    0 = > array (
      0 => "David", 
      1 => "541" 
     ), 

    1 = > array (
      0 => "Gruce", 
      1 => "162" 
     ), 

    2 = > array (
      0 => "Proman", 
      1 => "743" 
     ) 
) 

回答

7

试试这个:

var data = []; 

$('span.parent').each(function() { 
    var $this = $(this); 
    data.push({ 
     'name' : $this.find('span.childOne').text(), 
     'number' : $this.find('span.childTwo').text() 
    }); 
}); 

BTW:jQuery使用Sizzle选择器引擎。您应该在类之前定义元素类型,如span.parent。这要快得多。

+0

另一件事:如果您在当前范围内不止一次访问$(本),你应该使用一个单独的变量:像变量$这一点。所以,jQuery不能包含这个元素两次或更多。 – BaggersIO 2011-02-11 11:48:17

+0

'data'here is literal array .. – OpenCode 2011-02-11 12:48:09

2

如果这是一个固定的结构,你可以这样做:

var data = []; 

$('.parent').each(function() { 
    data.push({ 
     'name': $(this).children('.childOne').text(), 
     'number': $(this).children('.childTwo').text() 
    }); 
}); 

编辑:显然忘了.text();)

0
$('.parent').each(function(index) { 
    alert($(this).find('.childOne').text()); 
    alert($(this).find('.childTwo').text()); 
    }); 

后,你可以把它们放到一个数组

+0

感谢Alexl你的答案 – OpenCode 2011-02-11 12:38:52

1

我已经做了工作example

var array= []; 


$('.parent').each(function(index) { 
    array.push({ 
     'name': $(this).children('.childOne').text(), 
     'number': $(this).children('.childTwo').text() 
    }); 
    }); 
alert(array[0].name);