javascript - 如何从在 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
但似乎无法让它工作。有小费吗?
解决方案
当您创建表时,您应该给每个“持续时间”类,然后遍历每个元素并将值存储为 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
推荐阅读
- c# - 如何向 C# 9 记录添加注释
- python - 无法在 PyCharm 中导入 arcpy
- html - 响应式登录/注册/信息/关于页面未正确调整大小
- reactjs - React 钩子中的状态不会立即改变
- java - Jda discord bot 托管 heroku 问题
- java - Azure Monitor 应用程序启动/停止时间
- selenium - 保持浏览器窗口打开并重用 - Codeception Selenium Chrome Debian
- javascript - 如何从href调用javascript方法?
- python - python 3.9版中的blpapi
- html - 使用 RMarkdown 中的函数绘制要编织到 html 的绘图时出错