gpt4 book ai didi

javascript - 尝试对动态 HTML 表格列的值求和

转载 作者:行者123 更新时间:2023-12-01 00:08:04 26 4
gpt4 key购买 nike

我正在尝试对第二列中的值进行求和(标题标题='Value'),但它目前始终输出 0。我缺少什么??

(该表也是由 JavaScript 函数填充的,我已将其包含在该问题的底部)。

HTML:

<table id="output_table">
<tr>
<th>Name</th>
<th>Value</th>
</tr>
<tfoot>
<tr>
<th id="total" colspan="1">Total CPC:</th>
<td id="sum1"></td>
</tr>
</tfoot>
</table>

JS:

// code to sum CPC column
var sum1 = 0;
$("#output_table Value").each(function() {
sum1 += getnum($(this).find("td:eq(1)").text());
function getnum(t){
if(isNumeric(t)){
return parseInt(t,10);
}
return 0;
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
}
});
$("#sum1").text(sum1);

填充表的 JS:

 $('#sales_order_form_button').click(function(){
let table_info = [];
$('.campaignstrategy input[type=checkbox]').each(
function(index, value){
if($(this).is(':checked')){
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
}
);
}
});
let base64str=btoa(JSON.stringify(table_info));

window.location = "sales_order_form.html?table_data=" + base64str;
});

// Helper function
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

// actual code
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));

for(let i=0;i<data_from_page_1.length;i++){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text(data_from_page_1[i].name);
let recordValue = $("<td></td>").text(data_from_page_1[i].value);
row.append(recordName, recordValue);
$('#output_table').append(row);
}

最佳答案

如果您有tbody,它会让选择变得更容易:

var total = $('tbody td:nth-child(2)').toArray().reduce(function (sum, el) {
var value = isNaN($(el).text()) ? 0 : parseInt($(el).text(), 10);
return sum + value;
}, 0);

$('#sum1').text(total);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr> <th>Name</th><th>Value</th> </tr>
</thead>
<tbody>
<tr> <td>A</td><td>2</td> </tr>
<tr> <td>B</td><td>5</td> </tr>
<tr> <td>C</td><td>3</td> </tr>
</tbody>
<tfoot>
<tr> <td>Total CPC:</td><td id="sum1"></td> </tr>
</tfoot>
</table>

关于javascript - 尝试对动态 HTML 表格列的值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60233440/

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