gpt4 book ai didi

javascript - jQuery - 计算一个 td 内两个数字的总和并在新 td 内显示?

转载 作者:行者123 更新时间:2023-11-30 11:36:00 25 4
gpt4 key购买 nike

你好 Stackoverflowers,

我有这个代码:

    <table class="table">
<tbody>
<tr>
<td><a href="#">New thing</a></td>
<td>2017/06/04 08:00</td>
<td><a href="#">One Thing</a><span>Another thing</span></td>
<td class="random">R</td>
<td><a href="#">12-11 </a></td>
</tr>
<tr>
<td><a href="#">New thing</a></td>
<td>2017/06/04 08:00</td>
<td><a href="#">One Thing</a><span>Another thing</span></td>
<td class="random">R</td>
<td><a href="#">22-23 </a></td>
</tr>
</tbody>
</table>

在结果中,我想使用 jQuery 获取最后一个表 TD 中的数字总和并将其显示到新的 TD 中。就像下面的代码:

<table class="table">
<tbody>
<tr>
<td><a href="#">New thing</a></td>
<td>2017/06/04 08:00</td>
<td><a href="#">One Thing</a><span>Another thing</span></td>
<td class="random">R</td>
<td><a href="#">12-11 </a></td>
<td>[ 23 ]</td>
</tr>
<tr>
<td><a href="#">New thing</a></td>
<td>2017/06/04 08:00</td>
<td><a href="#">One Thing</a><span>Another thing</span></td>
<td class="random">R</td>
<td><a href="#">22-23 </a></td>
<td>[ 45 ]</td>
</tr>
</tbody>
</table>

提前致谢。

最佳答案

  1. 使用.each() 遍历所有tr
  2. 使用.text()获取文本
  3. 使用.append()tr的最后写入新的td
  4. 根据需要使用parseInt()parseFloat()Number()

//iterate all tr in table 
$('.table tr').each(function() {
// using this context to point to each tr get the last td using .last().
// use .text() to get its text
var tdval = $(this).find('td').last().text();

// use split and get the first value using index 0
var first = parseInt(tdval.split('-')[0])

// use split and get the second value using index 1
var second = parseInt(tdval.split('-')[1])

// use append to append the td where you will show the sum of two number.
// append will put the td in last
$(this).append("<td>" + (first + second) + "</td>")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<tbody>
<tr>
<td><a href="#">New thing</a></td>
<td>2017/06/04 08:00</td>
<td><a href="#">One Thing</a><span>Another thing</span></td>
<td class="random">R</td>
<td><a href="#">12-11 </a></td>
</tr>
<tr>
<td><a href="#">New thing</a></td>
<td>2017/06/04 08:00</td>
<td><a href="#">One Thing</a><span>Another thing</span></td>
<td class="random">R</td>
<td><a href="#">22-23 </a></td>
</tr>
</tbody>
</table>

关于javascript - jQuery - 计算一个 td 内两个数字的总和并在新 td 内显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44388428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com