我正在尝试添加“q-total”类中的所有值,但我无法让它工作。代码如下:
$(document).on("change", ".row-inputs", function(){
var total = 0;
var price = 0;
var multi = 0;
$('.q-quantity', this).each(function(){
multi = $(this).val();
})
$(".q-price", this).each(function(){
price += +$(this).val() * multi;
})
$(".q-total", this).val(price);
for (var i = 0; i < $(".q-total").length; i++) {
// total = 0;
// console.log($(".q-total", this).val() )
total += parseInt($(".q-total", this).val());
}
console.log("Total " + total)
})
下面是我用来向 html 添加新行的类代码。如果这可能有助于找出为什么上面的代码不起作用。
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + "
inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.className = "row-inputs";
newdiv.innerHTML = "<input type='text' name=''
placeholder='product name' class='q-product-name'> " +
"<input type='number' name='' placeholder='0' class='q-quantity'
value=1> " +
"<input type='text' name='' placeholder='price' class='q-price'> "
+
"<input type='text' name='' placeholder='price' class='q-total'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
谢谢
最佳答案
你的循环不正确:
改变
for (var i = 0; i < $(".q-total").length; i++) {
// total = 0;
// console.log($(".q-total", this).val() )
total += parseInt($(".q-total", this).val());
}
至
$(".q-total").each(function(){
total += +$(this).val();
})
在原始的 for
循环中,您从不迭代这些值,您总是采用 $(this).val()
。不确定为什么您与在其他地方使用的 .each()
方法不同,但这就是您的解决方案。
为了进一步解释,使用添加价格为 3,4,5 的行的示例。第一次通过(第一行),jQuery 集合中有一个元素,因此 total=0
变为 total += 3
;添加了第二行,您有两个元素,但只查看当前行的值,因此 total=0
变为 total += 4
&& total += 4
因此 total=8
;在第三行更改中,有三个元素,total = 15
( 3 * 5);
关于javascript - 在 Javascript 中计算类列表的值时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48957082/