您好我得到了以下jquery片段(请参阅jsfiddle)以计算行数。
另外我想用grand-total计算百分比。我试着在我自己添加一些代码来计算百分比,但我找不到它。我是jquery的noob,所以我需要你的帮助。
$(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;
}
请帮助我!!
答案 0 :(得分:1)
您可以这样做(这会在每个输入被修改后的每一行中添加一个列:
$(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/