我有一张 table ,上面有不同的 <td>
类名。我需要将其中每一项相加/求和以获得一个总值(value)。如果它们都有相同的类名,我可以很容易地做到这一点,但我不知道如何使用不同的类来做到这一点。因此,在下面的表格示例中,我需要添加 .price1 + .price2 + .price3 并将结果显示在 #result 中。
HTML:
<table id="tableOrderTotal" class="table tableTotal">
<tbody>
<tr>
<td>Item1</td>
<td class="price1">5</td>
</tr>
<tr>
<td>Item2</td>
<td class="price2">15</td>
</tr>
<tr>
<td>Item3</td>
<td class="price3">25</td>
</tr>
<tr class="summary">
<td class="totalOrder">Total:</td>
<td id="result" class="totalAmount"></td>
</tr>
</tbody>
</table>
最佳答案
尝试这个选择器,使用通配符
$("[class^=price]")
代码是
var result=0;
$("[class^=price]").each(function(e,i){result+=parseInt(i.innerHTML)});
console.log(result) // u get to see the result in console
关于javascript - 如何使用 js 或 jQuery 添加不同 div 类的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40028562/