嗨,我得到了以下 jquery 片段(请参阅 jsfiddle )来按行计算总和。
另外我想使用总计来计算百分比。我尝试在自己的代码中添加一些代码来计算百分比,但我无法成功找到它。我是 jquery 菜鸟,所以我需要你的帮助。
$(function() {
var total = 0,
$tableTotal = $('.result');
$('tr[data-total]').each(function() {
var $row = $(this);
total += $row.data('total');
$row.find('input').each(function() {
var $input = $(this);
$input.data('value', parseVals($input.val()))
$input.keyup(function() {
var currRowTot = $row.data('total');
var currInputVal = parseVals($input.val());
var diff = currInputVal - $input.data('value');
$input.data('value', currInputVal)
var newRowTot = currRowTot + diff;
$row.data('total', newRowTot).find('.total').text(newRowTot)
$tableTotal.trigger('changeTotal', [diff])
});
});
})
$tableTotal.data('total', total).val(total).on('changeTotal', function(e, rowDiff) {
var currTotal = $(this).data('total') + rowDiff;
$(this).data('total', currTotal).val(currTotal);
})
});
function parseVals(val) {
return (val != '') ? parseInt(val) : 0;
}
请帮助我!!
最佳答案
您可以这样做(这会向每一行添加一列,其中包含修改每个输入后计算出的百分比:
$(function() {
var total = 0,
$tableTotal = $('.result');
$('tr[data-total]').each(function() {
var $row = $(this);
total += $row.data('total');
$row.find('input').each(function() {
var $input = $(this);
$input.data('value', parseVals($input.val()))
$input.keyup(function() {
var currRowTot = $row.data('total');
var currInputVal = parseVals($input.val());
var diff = currInputVal - $input.data('value');
$input.data('value', currInputVal)
var newRowTot = currRowTot + diff;
$row.data('total', newRowTot).find('.total').text(newRowTot)
$tableTotal.trigger('changeTotal', [diff]);
var tableTotalSum = $tableTotal.val();
var percent = newRowTot * 100 / tableTotalSum;
$rowPercent = $row.find('.percent')
var percentage = percent.toFixed(2);
$rowPercent.text(percentage);
otherPercentage = 100 - percentage;
$rowPercent.closest('table').find('.percent').not($rowPercent).text(otherPercentage .toFixed(2));
});
});
})
$tableTotal.data('total', total).val(total).on('changeTotal', function(e, rowDiff) {
var currTotal = $(this).data('total') + rowDiff;
$(this).data('total', currTotal).val(currTotal);
return currTotal;
})
});
function parseVals(val) {
return (val != '') ? parseInt(val) : 0;
}
在这里摆弄http://jsfiddle.net/Mpayr/28/
编辑 - 有一个错误,我更正了我的代码
编辑- 2 再进行一次编辑以纠正小故障 http://jsfiddle.net/Mpayr/30/
关于jquery - jquery 计算总数的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8531732/