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

Adding all the values that has same class using jQuery

这是我的 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">

我正在尝试添加具有相同 class 名称 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

您需要访问 元素的值

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

您需要传递正确的对象名称。 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">

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

$('.tt').each(function(i, obj) {
    var value = $( obj ).val();

    console.log( value );
});

给你一个解决方案

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">

希望对您有所帮助。

此处,此函数将所有值相加 returns 总和。

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">