我有一个函数,通过id获得表行,然后我想在每行中获得每个span,这些将有一个'total-span'类,并与它们做一些事情。我遇到的问题是,一旦我有了行,就可以按类获取跨度。
任何帮助都非常感谢。
感谢function fieldTotals() {
var calculatedFields = document.getElementsByClassName("field-total");
Array.from(calculatedFields).forEach((el) => {
var _id = el.id;
var _rows = document.getElementById("electric-totals-" + _id);
//this next bit is what I can't get to work
Array.from(_rows).forEach((item) => {
var _spans = $(item).find(".total-span"); //something like this?
// then for each span get the int val of the innerHtml and sum them
});
});
}
您可以在行上使用querySelectorAll
并获得所有span元素。然后用reduce
函数计算和。
Array.from(_rows).forEach((item) => {
let _spans = item.querySelectorAll('.total-span');
if ( _spans == null ) return;
let sum = Array.from(_spans).reduce((sum, span) => sum + parseInt( span.innerHTML ), 0);
});