您好我正在尝试使用JavaScript代码对HTML表进行一些计算
但我在获取百分比值方面存在问题
演示:jsfiddle
当我输入以下样本数据时,我得到了这个结果
Percentage
0.16
0.33
0.5
因为你可以看到百分比值是错误的
百分比=总计/总计
所以百分比值应该是这样的
<script>
$(document).ready(function () {
$(".txtMult input").keyup(multInputs);
function multInputs() {
var mult = 0;
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1) * ($val2);
var $Percentage = ($total / mult) * 100;
$('.percentage', this).text($Percentage);
$('.multTotal', this).text($total);
mult += $total;
});
$("#grandTotal").text(mult);
}
});
</script>
Javascript
<table>
<tr>
<th>Quantity
</th>
<th>Unit Price
</th>
<th>Total
</th>
<th>Percentage
</th>
</tr>
<tr class="txtMult">
<td>
<input name="txtbox1" class="val1" />
</td>
<td>
<input name="txtbox2" class="val2" />
</td>
<td>
<span class="multTotal">0.00</span>
</td>
<td>
<span class="percentage">0</span>
</td>
</tr>
<tr class="txtMult">
<td>
<input name="txtbox1" class="val1" />
</td>
<td>
<input name="txtbox2" class="val2" />
</td>
<td>
<span class="multTotal">0.00</span>
</td>
<td>
<span class="percentage">0</span>
</td>
</tr>
<tr class="txtMult">
<td>
<input name="txtbox" class="val1" />
</td>
<td>
<input name="txtbox" class="val2" />
</td>
<td>
<span class="multTotal">0.00</span>
</td>
<td>
<span class="percentage">0</span>
</td>
</tr>
<tr>
<td colspan="3" ">Grand Total <span id="grandTotal">0.00</span>
</td>
</tr>
</table>
HTML
func scrollToRowAtIndexPath(_ indexPath: NSIndexPath,
atScrollPosition scrollPosition: UITableViewScrollPosition,
animated animated: Bool)
非常感谢您的帮助
答案 0 :(得分:1)
这是我在小提琴中测试的一些可用的JS代码:
$(document).ready(function () {
$(".txtMult input").keyup(multInputs);
function multInputs() {
var $mult = 0;
// calculate Grand total
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1) * ($val2);
$mult += $total;
});
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1) * ($val2);
var $Percentage = (($total / $mult)).toFixed(2);
$('.percentage', this).text($Percentage);
$('.multTotal', this).text($total);
});
$("#grandTotal").text($mult);
}
});
我首先计算了总计,然后将每行总计除以总计。此外,如果需要,.toFixed(2)可用于舍入到2位小数。