使用jQuery添加具有相同类的所有值

时间:2017-11-17 06:23:40

标签: javascript jquery html each

这是我的HTML

<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">

我正在尝试添加具有相同类名tt

的所有值

所以我这样做

$('.tt').each(function(i, obj) {
    var oo = obj;
    console.log(oo)
});

当我做console.log(00)

打印

<input type="hidden" class="tt to_5" value="35">

但是当我尝试做的时候

console.log(oo.val())

显示undefined如何获取值?

使用jQuery

5 个答案:

答案 0 :(得分:1)

您需要访问元素的值

var total = 0;
$('.tt').each(function(i, obj) {
    console.log(obj.value)//value is printed
    total += Number(obj.value);
});

答案 1 :(得分:1)

如果要记录值,请执行以下操作:

{{1}}

答案 2 :(得分:1)

您可以使用解决方案

var total = 0;
$('.tt').each(function(){
  console.log("Current Value:", $(this).attr('value'));
  total += parseInt($(this).attr('value'));
});

console.log("Total: ",total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">

希望这会对你有所帮助。

答案 3 :(得分:0)

您需要传递正确的对象名称。 each内回调的第二个参数指向对象,使用它可以访问输入标记的值。

$('.tt').each(function(i, o) {
    console.log($(o).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">

答案 4 :(得分:0)

此处,此函数将所有值相加并返回总和。

function getSum() {
   var total = 0;
   $('.tt').each(function(i, obj) {   
      total += Number(obj.value);
   });

   return total;
}

console.log(getSum());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" class="tt to_5" value="35">
<input type="hidden" class="tt to_6" value="15">
<input type="hidden" class="tt to_7" value="25">