javascript - 如何使用 js 或 jQuery 添加不同 div 类的值

标签 javascript jquery html

我有一张 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/

相关文章:

javascript - Node Js Express 遍历数组

javascript - 某些 URL 的 Jsdom 抛出错误

javascript - 在下拉菜单中输入字符时,它会从选项中选择任何随机匹配项并触发更改事件

javascript - 根据第一个选择设置第二个选择的选项

javascript - 复选框隐藏 Div 未选中

html - PrimeNg 的 <pcalender> 中的日期验证逻辑

javascript - 如何使用 CSS 在 AngularJS 中换行文本?

JavaScript - 将字符串拆分为单词、识别元音最多的单词的函数 - 使用 For 循环

javascript - 查找 Backbone 中所有选中的复选框

javascript - 在数据刷新时为 flexbox 列设置动画