如何从在AJAX中创建的表中获取“内部文本”中的项的总和?

我有一个代码,它使用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



UYOU
浏览 58回答 1
1回答

忽然笑

创建表时,应为每个“持续时间”类指定,然后循环访问每个元素并将值存储为 int。例如:<table id="testtable">&nbsp; <tr>&nbsp; &nbsp; <th>Date</th>&nbsp; &nbsp; <th>Duration</th>&nbsp; </tr>&nbsp; <tr class="duration"><td >5</td><td class="duration">5</td></tr></table><script>jQuery(document).ready(function(){&nbsp; &nbsp; // Loop through each div element with the class boxtotal =0;&nbsp; &nbsp; $(".duration").each(function(){&nbsp; &nbsp; &nbsp; &nbsp; stringval = jQuery(this).text();&nbsp; &nbsp; &nbsp; &nbsp; num = parseInt(stringval);total += num;&nbsp; &nbsp; &nbsp; &nbsp; ;&nbsp; &nbsp; });&nbsp; &nbsp; console.log(total);});'''</script>这将返回10
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript