首页 > 解决方案 > 通过 Jquery 在动态 HTML 表的单元格中执行计算

问题描述

我基本上是在动态表格单元格中执行计算想要在用户更改单元格值时更改单元格值的总和

我已经尝试过不同的 jquery 方法,但没有得到我想要的

<table class="table table-responsive table-hover table-bordered" id="tablefinaldata">
<thead>
    <tr>
        <td>
            <h5> Code</h5>
        </td>
        <td>
            <h5> Item</h5>
        </td>
        <td>
            <h5> Price</h5>
        </td>
        <td>
            <h5> Quantity</h5>
        </td>
        <td>
            <h5> Sub Total</h5>
        </td>
    </tr>
</thead>
<tbody id="tablefinalbody">

</tbody>

function CalSum ()
    {
        $("#setfinaldata #subtotal").each(function () {
            var row = $(this);
            var rowTotal = 0;
            $(this).find('th').each(function () {
                var th = $(this);
                if ($.isNumeric(th.text())) {
                    rowTotal += parseFloat(th.text());
                }
            });
            row.find('th:last').text(rowTotal);
        });
    }

标签: javascriptjqueryhtml

解决方案


function CalSum() {
  var $trList = $("#tablefinalbody").find('tr');
  var rowTotal = new Array($trList.length);
  $trList.each(function() {
    var row = $(this);
    $(this).find('th').each(function(index) {
      var th = $(this);
      if ($.isNumeric(th.text())) {
        if (!rowTotal[index]) rowTotal[index] = 0
        rowTotal[index] += parseFloat(th.text());
      }
    });
  });

  $trList.last().children().each(function(index) {
    $(this).text(rowTotal[index])
  })
}
CalSum();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-responsive table-hover table-bordered" id="tablefinaldata">
  <thead>
    <tr>
      <td>
        <h5> Code</h5>
      </td>
      <td>
        <h5> Item</h5>
      </td>
      <td>
        <h5> Price</h5>
      </td>
      <td>
        <h5> Quantity</h5>
      </td>
      <td>
        <h5> Sub Total</h5>
      </td>
    </tr>
  </thead>
  <tbody id="tablefinalbody">
    <tr>
      <th>1</th>
      <th>2</th>
      <th>3</th>
      <th>4</th>
      <th>5</th>
    </tr>
    <tr>
      <th>123</th>
      <th>42</th>
      <th>53</th>
      <th>64</th>
      <th>234</th>
    </tr>
    <tr>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </tbody>
</table>


推荐阅读