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

How to use operations based on the number of user inputs?

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

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