[英]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.