我一直在尝试将JQUERY函数转换为JavaScript。我不确定我做错了什么。我在JS中重写函数时返回的值都返回0.0。
以下是我想要转换为纯JavaScript的JQUERY代码:
$('#tableID > tbody > tr > td:nth-child(' + starter + ')').each(function () {
getAverage('#tableID > tbody > tr > td:nth-child(' + starter + ')', 'subTotal');
})
基本上我想删除.each()并使用原生JavaScript代替......
以下是完整代码:
var el1 = $('#tableID > thead > tr > th:gt(17):not(.totalRow)');
var x = el1.length;
var starter = 19;
for (i = 0; i < x; i++) {
$('#tableID > tbody > tr > td:nth-child(' + starter + ')').each(function () {
getAverage('#tableID > tbody > tr > td:nth-child(' + starter + ')', 'subTotal');
})
starter += 1;
}
以下是帮助了解正在发生的事情的getAverage函数:
//average function
function getAverage(a, b) {
var $this, $content, tdTxt, theAvg;
var sum = 0;
var count = 0;
$(a).each(function () {
$this = $(this); // cache $(this)
$content = $this.html();
tdTxt = parseFloat($this.text(), 10) || 0;
if ($this.hasClass(b)) {
theAvg = parseFloat((sum / count), 10) || 0;
$this.text((theAvg).toFixed(2));
sum = 0;
count = 0;
} else {
sum += parseFloat(tdTxt);
if ($content == '') {
}
else {
++count; // this micro-optimization makes it marginally faster
}
}
})
}
答案 0 :(得分:1)
Array.from(
document
.querySelectorAll('#tableID > tbody > tr > td:nth-child(' + starter + ')')
).forEach(_=> getAverage(
'#tableID > tbody > tr > td:nth-child(' + starter + ')',
'subTotal'
))