首页 > 解决方案 > 如何使用 jQuery 自动对 html 中的行求和?

问题描述

我想自动对 html 中的行求和,然后使用 jQuery 显示结果我试过但我失败了,下面是我使用循环的示例代码

<html>
<head>
<title></title>
    
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js" /></script>
    
    

<script>
$.fn.fonkTopla = function() {
var toplam = 1;
this.each(function() {
   var deger = fonkDeger($(this).val());
   
   //get the data attr value
   var diff = $(this).data('diff');
   var Quantity_val = $(this).closest('tr').find('.Quantity').val();
   var QuantityBack_val = $(this).closest('tr').find('.QuantityBack').val();
   var UnitPrice_val = $(this).closest('tr').find('.UnitPrice').val(); 
   
   var paid_val = $(this).closest('tr').find('.paid').val();
   
   //On based on data attribute, if the input field is paid, do not multiply,
   if(!diff){
   //toplam *= deger;
   toplam= (Quantity_val * UnitPrice_val);
   
   //take the result minus paid field
   total = (toplam) - paid_val-(QuantityBack_val * UnitPrice_val);
   }
});
return total;
};


function fonkDeger(veri) {
    return (veri != '') ? parseInt(veri) : 1;
}

$(document).ready(function(){
$('input[name^="fiyat"]').bind('keyup', function() {

   //for multiple tr, get the closest tr field value to calculate and display
   $(this).closest('tr').find('.toplam').html( $(this).closest('tr').find('input[name^="fiyat"]').fonkTopla());
});
});
</script>

</head>
<body>




<?php
for($counter1=0;$counter1<=2;$counter1++)
{
?>
<table>
<?php
for($counter2=0;$counter2<=2;$counter2++)
{
?>
<tr>
<td><input type="number" name="fiyat[]" class="Quantity" /></td>
<td><input type="number" name="fiyat[]" data-diff="true"  class="QuantityBack" /></td>
<td><input type="number" name="fiyat[]" class="title UnitPrice" value="500" /></td>
<td><input type="number" name="fiyat[]" data-diff="true"  class="paid" /></td>
<td style="text-align:right" bgcolor="#FF5733"><span class="toplam"></span>
</tr>


<?php
}
?>
</table>
<?php
}
?>

<!--I NEED TO CALCULATE SUB TOTAL OF EACH TABLE IN LOOP IN BELOW CODES, I NEED SUB TOTAL UNDER LAST RED COLUMN-->
<script>
var totalRow = '', columnNo = $('table tr:first td').length;

for (var index = 0; index < columnNo; index++) {
    var total = 0;
    $('table tr').each(function () {
        total += +$('td', this).eq(index).text(); //+ will convert string to number
    });
    totalRow += '<td>' + total + '</td>';
}

$('table').append('<tr>' + totalRow + '</tr>');
</script>
<!--end of jQuery used to auto sum subtotal-->




</body>
</html>

问题出在 jQuery 中,这使得 Total(jQuery 位于代码的底部)请任何人都可以帮助我们完成这项任务。我只需要循环中每个表的小计,但在红色列中。谢谢

标签: htmljquery

解决方案


在这种情况下,你可以用 jQuery 做的是循环你的类选择器,toplamc在这种情况下,总结内容。

jQuery:

var sum = 0;
$('.toplamc').each(function() {
     sum += parseFloat($(this).text());
});
$('#sum').text(sum);

这适用于动态添加的内容。您只需要确保在创建动态内容之后运行该功能。请记住,代码是自上而下执行的。它找不到尚不存在的元素。

因此,如果您在总和已经计算过的情况下继续添加动态内容,则每次添加新行时都需要连续执行 sum 函数。

具有动态内容的片段示例:

$('#createRowsBtn').on("click", function() {    
    var classCount = $('.toplamc').length;
    if(classCount > 0) {
        $('#calcTable').html("");
    }
    
    var rowCount = $('#rowCount').val();
    if(rowCount < 1 || rowCount == "") {
        alert('enter a number bigger than 0 in the input field');
    } else {
        $('#another-container').css("visibility", "visible");
        var html  = '<tr>';
            html +=     '<td>';
            html +=         'random stuff';
            html +=     '<td>';
            html +=         'more random stuff';
            html +=     '</td>';
            html +=     '<td bgcolor="#FF5733">';
            html +=         '<span class="toplamc"></span>';
            html +=         'USD';
            html +=     '</td>';

        for(var i = 0; i < rowCount; i++) {
            $('#calcTable').append(html);
        }
        
        $('.toplamc').each(function() {
            var randomNum = Math.round(Math.random() * 10);
            $(this).text(randomNum);
        });
        
        var html  = '<tr>';
            html +=     '<td>';
            html +=         'Total';
            html +=     '<td>';
            html +=         'Sum';
            html +=     '</td>';
            html +=     '<td colspan="2">';
            html +=         '<span id="sum"></span>';
            html +=         'USD';
            html +=     '</td>';
            html += '</tr>';
        $('#calcTable').append(html);
        
        
        var sum = 0;
        $('.toplamc').each(function() {
             sum += parseFloat($(this).text());
        });
        $('#sum').text(sum);
    }
});

$('#addRowBtn').on("click", function() {
    var numVal = $('#newRowVal').val();
    
    if(numVal < 1) {
        alert('please enter a value greater than 0');
        $('#newRowVal').val("");
    } else {
        $('#sum').parent().parent().remove();
        
        var html  = '<tr>';
            html +=     '<td>';
            html +=         'random stuff';
            html +=     '<td>';
            html +=         'more random stuff';
            html +=     '</td>';
            html +=     '<td bgcolor="#FF5733">';
            html +=         '<span class="toplamc">'+numVal+'</span>';
            html +=         'USD';
            html +=     '</td>';
            html += '</tr>';
            html += '<tr>';
            html +=     '<td>';
            html +=         'Total';
            html +=     '<td>';
            html +=         'Sum';
            html +=     '</td>';
            html +=     '<td colspan="2">';
            html +=         '<span id="sum"></span>';
            html +=         'USD';
            html +=     '</td>';
            html += '</tr>';
            $('#calcTable').append(html);
            
        var sum = 0;
        $('.toplamc').each(function() {
             sum += parseFloat($(this).text());
        });
        $('#sum').text(sum);
    }
});
#another-container {
    visibility: hidden;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
    <div class="form-group col-md-8">
        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text rounded-0">Amount of rows:</span>
            </div>
            <input type="number" class="form-control rounded-0" id="rowCount" min="1" placeholder="number of rows" />
            <button class="btn-primary" id="createRowsBtn">Create rows</button>
        </div>
    </div>
</div>
<br />
<table class="table table-dark" id="calcTable">
</table>
<div class="row" id="another-container">
    <div class="form-group col-md-8">
        <div class="input-group">
            <div class="input-group-prepend">
                <span class="input-group-text rounded-0">Another row?:</span>
            </div>
            <input type="number" class="form-control rounded-0" id="newRowVal" min="1" placeholder="add 1 more row with a fixed value" />
            <button class="btn-primary" id="addRowBtn">Add row</button>
        </div>
    </div>
</div>

Codepen 示例在这里

更多关于 jQuery.each()函数的信息在这里


推荐阅读