将特定列相加或相乘

Add or Multiply Specific columns together

我看过一些 jquery 和添加列值的示例;但是,示例只有一列和一个值。

我想知道如果您有多个列,那么您如何抓取特定的列?

例如,如果我想将所有数量列加在一起将成本列与其相邻的数量相乘?

到目前为止,我已经开始设置,但它不起作用。最初我试过

 child_nodes.eq(2).text() 

获取数量列,但我知道我的逻辑不对。

$(document).ready(function() {

$('#checkout').on('click', function() {

        item_count();
});
});

function item_count(){

    $('.product').each(function() {

        //find number of child nodes
        var child_nodes = $(this).text(); //children returns all

        var count = "";
        for (var i=0; i<child_nodes.length; i++){
        //whole row output
        count += child_nodes.eq(i).text() + "\n";
        }
    });

    //var total = parseInt($('.product').val());
    var total += parseInt(count);
    //update value
    return $('#nitems').text(total);

};

我刚开始尝试 j 查询,所以我觉得我的代码看起来很菜鸟,所以我进行了类比。

<h4>Shopping Cart</h4>
 <table class='table'>
  <thead>
    <tr>
      <th>Product</th><th>Unit cost</th><th>Quantity</th>
    </tr>
  </thead>
  <tbody>
    <tr class='product'>
      <td>Milk Chocolate</td>
      <td>7.48</td>
      <td>5</td>
    </tr>
    <tr class='product'>
      <td>Assorted Fine Chocolates</td>
      <td>9.98</td>
      <td>7</td>
    </tr>

    <tr class='product'>
      <td>Assorted Milk & Dark Chocolates</td>
      <td>12.98</td>
      <td>9<td>
    </tr>

    <tr class='product'>
      <td>Assorted Dessert Truffles</td>
      <td>15.98</td>
      <td>4</td>
    </tr>
   </tbody>
  </table>
</div>
</div>
<div class='row'>
<div class='col-md-4'>

  <h3>Finalize Sale </h3>
  <table class='table'>
    <tr>
      <td>Total Items</td>
      <td><span  id="nitems" >0</td>
    </tr>
    <tr>
      <td>Subtotal</td>
      <td><span  id="subtotal" >0</td>
    </tr>
    <tr>
      <td>5% Sales tax</td>
      <td><span id="tax" >0</td>
    </tr>
    <tr>
      <td>Total</td>
      <td><span id="total" >0</td>
    </tr>
    <tr>
      <td>Final amount (with 15% discount)</td>
      <td><span id="final"  >0</td>
    </tr>
  </table>

.each 函数应采用一个将用作迭代器的变量。改变这个:

$('.product').each(function() {

至此

$('.product').each(function(index, val) {

然后在里面,您应该可以访问每个 TD。

此外,这一行:

count += child_nodes.eq(i).text()

将为您提供 5794 的值。它附加每个字符串,而不是添加 int 值。你会想要这样的东西:

count += parseInt($("td", val).eq(3)), 10);

总而言之,我会这样做...

function item_count(){

    var count = 0;

    $('.product').each(function(index, val) {

        var total += parseInt($("td", val).eq(3), 10);
    }       

    $('#nitems').val(total);
};

请注意,这一切都未经测试,因此可能需要进行一些调整。