jquery:获取div的所有子节点的值

时间:2012-12-13 09:49:31

标签: jquery

我正在尝试使用jquery来获取div的所有子元素的值。

<div class='parent'>
    <input type='text' value='1' class='child' />
    <input type='text' value='2' class='child' />
    <input type='text' value='3' class='child' />
    <input type='text' value='4' class='child' />
</div>

使用db从php生成子输入。他们的人数各不相同。

我想得到类似的东西:

variable = (child1_value + child2_value + child3_value + child4_value + ... + "childX_value");

我怎样才能为不同数量的孩子做这项工作?

5 个答案:

答案 0 :(得分:4)

你可以使用每个......

var total = 0;

$(".child").each(function() {
    total += parseInt($(this).val());
});

或类似的

答案 1 :(得分:3)

var value = 0;
$('.parent input').each(function() {
  value += parseInt($(this).val());
});

答案 2 :(得分:1)

添加这些值。

<强> Live Demo

sum = 0;
$('.parent :input').each(function(){     
      sum+= parseFloat($(this).val());
})
alert(sum);

答案 3 :(得分:1)

试试这个,

$(document).ready(function(){
    var array = [];
    $('.child').each(function(){
       array.push($(this).val()); // store in an array for reuse
    });
    var total = 0;
    for (var i = 0; i < array.length; i++) {
        total += parseInt(array[i]); // sum up values in the array
    }
    alert(total);
});

答案 4 :(得分:0)

var result = 0;
$("input").each(function(index,value){ 
  result += parseFloat($(this).val());
});

Demo: http://jsfiddle.net/JmsAb/1/