gpt4 book ai didi

javascript - 如何使用基于用户输入数量的操作?

转载 作者:行者123 更新时间:2023-12-02 16:22:44 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的计算器,它可以根据学生的成绩告诉他们他们的平均大学分数。

JSFiddle

我正在尝试获取执行此操作的公式:
第 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

});

演示:Fiddle

关于javascript - 如何使用基于用户输入数量的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28955909/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com