首页 > 解决方案 > 如何从在 AJAX 中创建的表中获取“innerText”内的项目总和?

问题描述

我有一个代码,它使用 AJAX 从数据库中的项目向表中添加行。那部分工作正常,但我需要计算我创建的行中的数字的总和,但由于某种原因,我尝试的一切都不起作用。

我的代码:

$.ajax({
      type: "GET",
      url: "http://localhost:8080/api/001,
      dataType: "json",

      success: function(data) {

        for (var count = 0; count < data.length; count++) {

          $('<tr>').append(
            $('<td>').text(dateArray[0]),
            $('<td class="duration">').text(dateArray[1]),

          ).appendTo('#testtable');

        },
        error: function(jqXHR, textStatus, errorThrown) {}
      });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="testtable">
  <tr>
    <th>Date</th>
    <th>Duration</th>
  </tr>

这成功地将数据插入到表中,但我试图得到总和Duration但似乎无法让它工作。有小费吗?

标签: javascripthtmlajax

解决方案


当您创建表时,您应该给每个“持续时间”类,然后遍历每个元素并将值存储为 int。然后总结这些值。例如 :

<table id="testtable">
  <tr>
    <th>Date</th>
    <th>Duration</th>
  </tr>
  <tr class="duration"><td >5</td><td class="duration">5</td></tr>
</table>

<script>


jQuery(document).ready(function(){
    // Loop through each div element with the class box
total =0;
    $(".duration").each(function(){
        stringval = jQuery(this).text();
        num = parseInt(stringval);
total += num;
        ;


    });
    console.log(total);
});'''
</script>

这将返回 10


推荐阅读