jQuery计算平均值和排序结果

时间:2020-09-17 07:26:10

标签: jquery

我需要使用jQuery添加功能:

  1. 添加行(已完成)
  2. 计算输入的平均分数。更换 ”?”在列中。
  3. 对于平均得分> = 8,该行将用红色突出显示。

我应该对每个后两个函数使用each()和children()。但是作为一个初学者,我觉得这非常令人困惑。

$(document).ready(function() {
  var _stt = 1;
  $("#btn-add").click(function() {
    var name = $('input[name="name"]').val();
    var math = $('input[name="math"]').val();
    var physic = $('input[name="physic"]').val();
    var chemistry = $('input[name="chemistry"]').val();
    var calcdtb = "?";
    var addtr = '<tr> <td>' + _stt + '</td> <td>' + name + '</td> <td class="mark">' + math + '</td> <td class="mark">' + physic + '</td> <td class="mark">' + chemistry + '</td> <td class="result_dtb">' + calcdtb + '</td> </tr>';
    $("#inputtab").append(addtr);
    _stt++;
  });
  $("#btn-average").click(function() {

  })
  $("#btn-sort").click(function() {

  })

})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" align="center">
  <h1>Class Marksheet</h1>
  <form style="padding-bottom: 20px">
    <table border="0" cellpadding="0" cellspacing="0">
      <tr>
        <td width="100">Name</td>
        <td><input type="text" name="name" id="name"></td>
      </tr>
      <tr>
        <td width="100">Math Score</td>
        <td><input type="number" name="math" id="math"></td>
      </tr>
      <tr>
        <td width="100">Physics Score</td>
        <td><input type="number" name="physic" id="physic"></td>
      </tr>
      <tr>
        <td width="100">Chemistry Score</td>
        <td><input type="number" name="chemistry" id="chemistry"></td>
      </tr>
    </table>
  </form>
  <button type="submit" id="btn-add">Input</button>
</div>
<!--Div Tab for showing data input and calculating average value-->
<div class="tab" align="center" style="padding-top: 10px">
  <table id="inputtab" style="padding-top: 10px; padding-bottom: 10px">
    <th>List</th>
    <th>Name</th>
    <th>Math</th>
    <th>Physics</th>
    <th>Chemistry</th>
    <th>Average</th>
  </table>
  <button type="submit" id="btn-average">Average</button>
  <button type="submit" id="btn-sort">Top Student</button>
</div>

1 个答案:

答案 0 :(得分:0)

请研究以下代码:

  • 有效的HTML(thead / tbody / tfoot)
  • 如何使用子代的长度来计算行数
  • 从str转换为有效数字以避免NaN
  • 设置和获取数据属性
  • 使用三元(NavigationView { content }.navigationViewStyle(StackNavigationViewStyle()) )添加字符串
  • 通过从单元格b的平均值中减去单元格a的平均值进行排序

_calcdtb>8 ? 'class="high"':''
const makeNum = str => isNaN(str) || str.trim() === "" ? 0 : parseInt(str);
$(function() {
  $("#btn-add").click(function() {
    var _name = $('input[name="name"]').val();
    var _math = makeNum($('input[name="math"]').val());
    var _physic = makeNum($('input[name="physic"]').val());
    var _chemistry = makeNum($('input[name="chemistry"]').val());
    var _calcdtb = (_math + _physic + _chemistry) / 3;
    var _tr = '<tr ' + (_calcdtb >= 8 ? 'class="high"' : '') + '> <td>' + ($("#inputtab").children().length + 1) + '</td> <td>' + _name + '</td> <td class="mark">' + _math + '</td> <td class="mark">' + _physic + '</td> <td class="mark">' + _chemistry + '</td> <td class="result_dtb" data-avg="' + _calcdtb.toFixed(2) + '">?</td> </tr>';
    $("#inputtab").append(_tr);
    $("#inputForm")[0].reset();
  });
  $("#btn-average").on("click", function() {
    $("#inputtab tr td.result_dtb").each(function() {
      this.textContent = this.dataset.avg;
    })
  })
  $("#btn-sort").on("click", function() {
    $('#inputtab tr').sort(function(a, b) {
      return +$('td.result_dtb', b).data('avg') - +$('td.result_dtb', a).data('avg'); 
    }).appendTo('#inputtab')
  })
})

/* if you need to have the total avg here is the code

    const arr = $("#inputtab tr td.result_dtb")
     .map(function() { return +$(this).text() }) // content
     .get(); // as an array
    const sum = arr.reduce((a, b) => a + b, 0); // summing all values in the array
    const avg = sum/arr.length; // sum divided by number of lines
    $("#avg").text(avg.toFixed(2)); // force 2 decimals
*/
tr.high {
  background-color: red;
}

请注意,在现代浏览器中您可以更改

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" align="center">
  <h1>Class Marksheet</h1>
  <form id="inputForm"style="padding-bottom: 20px">
    <table border="0" cellpadding="0" cellspacing="0">
      <tbody>
        <tr>
          <td width="100">Name</td>
          <td><input type="text" name="name" id="name"></td>
        </tr>
        <tr>
          <td width="100">Math Score</td>
          <td><input type="number" name="math" id="math"></td>
        </tr>
        <tr>
          <td width="100">Physics Score</td>
          <td><input type="number" name="physic" id="physic"></td>
        </tr>
        <tr>
          <td width="100">Chemistry Score</td>
          <td><input type="number" name="chemistry" id="chemistry"></td>
        </tr>
      </tbody>
    </table>
  </form>
  <button type="button" id="btn-add">Input</button>
</div>
<!--Div Tab for showing data input and calculating average value-->
<div class="tab" align="center" style="padding-top: 10px">
  <table style="padding-top: 10px; padding-bottom: 10px">
    <thead>
      <th>List</th>
      <th>Name</th>
      <th>Math</th>
      <th>Physics</th>
      <th>Chemistry</th>
      <th>Average</th>
    </thead>
    <tbody id="inputtab"></tbody>
    <!-- tfoot><tr><td colspan="5"></td><td id="avg"></td></tfoot -->
  </table>
  <button type="button" id="btn-average">Average</button>
  <button type="button" id="btn-sort">Top Student</button>
</div>

对此(使用模板文字)

var _tr = '<tr '+(_calcdtb >= 8 ? 'class="high"':'')+'> <td>' + ($("#inputtab").children().length+1) + '</td> <td>' + _name + '</td> <td class="mark">' + _math + '</td> <td class="mark">' + _physic + '</td> <td class="mark">' + _chemistry + '</td> <td class="result_dtb" data-avg="'+_calcdtb.toFixed(2) + '">?</td> </tr>';

这更容易阅读