在帮助下,我已经获得了该脚本来将函数的类更改为包括可计数的,但需要获取总计算量以更新发生更改时显示的所有字段的总和。

脚本被拆分,其中最上面的一组用于计算所有可计数类字段的总数,第二个脚本部分用于显示订单项并添加可计数的类。

<script>
var totals=[0,0,0];
$(document).ready(function(){

    var $dataRows=$("#sum_table tr:not('.totalColumn, .titlerow')");

    $dataRows.each(function() {
        $(this).find('.countable').each(function(i){
            totals[i]+=parseInt( $(this).html());
        });
    });
    $("#sum_table td.totalCol").each(function(i){
        $(this).html("total:"+totals[i]);
    });

});
</script>
<script>
$(document).ready(function() {
  $("input[type=checkbox]").change(function() {
    var val = $(this).val();
    var isChecked = $(this).is(":checked");

    var $trElement = $('.' + val);
    var $tdPriceElement = $trElement.find('td.price');

    $trElement.toggle(isChecked);
    $tdPriceElement.toggleClass('countable', isChecked);
  });
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


通过选中这些复选框,可以显示订单项。

<input class="my-activity" type="checkbox" value="42"/> example<br/>
<input class="my-activity" type="checkbox" value="43"/> example<br/>

<table id="sum_table">
<tr class="42" style="display:none">
  <td>example</td>
  <td></td>
  <td></td>
  <td class="price">7800</td>
</tr>
<tr class="43" style="display:none">
  <td>First Area</td>
  <td></td>
  <td></td>
  <td class="price">6900</td>
</tr>
<tr class="totalColumn">
    <td>Total:</td>
    <td></td>
    <td class="totalCol"></td>
</tr>
</table>

最佳答案

您需要先加载jQuery,然后才能使用它,所以请移动:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


在其他2个脚本之上。然后,用以下代码替换您的第一个脚本:

function showTotal(){
    //grab the .countable elements from the #sum_table
    var $countables =$("#sum_table .countable");

    //loop through and add up the total from their texts
    var total = 0;
    for(var i = 0; i < $countables.length; i++){
        total += Number($countables.eq(i).text());
    }

    //put the total in the .totalCol element
    $("#sum_table td.totalCol").html(total);
}


并在onchange函数的末尾调用此函数,如下所示:

$(document).ready(function() {
  $("input[type=checkbox]").change(function() {
    var val = $(this).val();
    var isChecked = $(this).is(":checked");

    var $trElement = $('.' + val);
    var $tdPriceElement = $trElement.find('td.price');

    $trElement.toggle(isChecked);
    $tdPriceElement.toggleClass('countable', isChecked);

    //CALL IT HERE:
    showTotal();
  });
});

关于javascript - 在没有输入字段的情况下使用新复选框刷新javascript计算的总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59366663/

10-09 15:24