[英]How to use operations based on the number of user inputs?
我正在尝试制作一个简单的计算器,该计算器可以根据学生的成绩告诉他们他们的平均大学成绩。
我试图获得公式来做到这一点:
步骤1 :(标记*信用点)
步骤2:将这些总计加在一起
第3步:获取总数,然后除以用户输入的数量。
在执行第2步和第3步时遇到麻烦。现在,单击“计算”时,它只是将每一行的单个答案一个接一个地追加。 我想将这些值相加然后除以输入数量。(因为主题的数量在用户之间会有所不同)
任何帮助都非常感谢。
HTML:
<div>
<table class='table'>
<tr>
<th> Unit Code </th>
<th> Mark </th>
<th> Credit Point </th>
</tr>
<tr>
<td> <input type="text"></td>
<td> <input type="text" class='mark'> </td>
<td> <input type="text" class='creditPoint'> </td>
</tr>
<tr>
<td> <input type="text"></td>
<td> <input type="text" class='mark'> </td>
<td> <input type="text" class='creditPoint'> </td>
</tr>
<tr>
<td> <input type="text"></td>
<td> <input type="text" class='mark'></td>
<td> <input type="text" class='creditPoint'> </td>
</tr>
</table>
</div>
Javascript:
$('#wam').click(function() {
$('.table tr').each(function() {
var mark = $(this).find('input.mark').val();
var cp = $(this).find('input.creditPoint').val();
var total = ((mark * cp));
// Find the total then divide by the number of entries
$('body').append(total);
});
});
您需要在循环中使用共享变量
$('#wam').click(function () {
var total = 0,
count = 0;
$('input.mark').each(function () {
var mark = this.value;
var cp = $(this).parent().next().find('input.creditPoint').val();
var t = mark * cp || 0;//if both the fields are not entered don't add them
if (t) {
//if the product is 0 then don't count the value
count++;
}
total += t;
});
$('#total').text(total);
$('#total2').text(count ? total / count : 0);//the ternary condition to prevent division by 0
});
演示: 小提琴
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.