如何解决我在html中的功能无法正常运行
我制作了一个函数来计算平均值,并尝试在每个部分中使用此函数。但是计算无法正常进行。如果您看到下面的代码,则handleCalculateAverageButtonClick('Question1')函数在第一节中起作用(节类=“ Question1”),但是handleCalculateAverageButtonClick('Question2')函数的计算在第二节中是错误的(第二类=“ Question2” )。我的代码中需要修改吗?
<section class = "Question1">
how many times do you want to buy on scale?
<input type = "number" style = "height : 20px ; width: 50px; " class = "scale-count" />
<button type = "button" onclick = "handleNextButtonClick('Question1')" style = "padding
: 4px 19px;">
Next
</button>
<div class = "form-output"> </div>
<br>
<button class = "button button1" onclick =
"handleCalculateAverageButtonClick('Question1')">
CalculateAverage
</button> :
<span class= "average1"></span>
</section>
<section class = "Question2">
How many times do you want to sell on scale?
<input type = "number" style ="height : 20px; width: 50px;" class = "scale-count" />
<button type = "button" onclick = "handleNextButtonClick('Question2')" style =
"padding:4px 19px;">
Next
</button>
<div class = "form-output"></div>
<br>
<button class = "button button1" onclick =
"handleCalculateAverageButtonClick('Question2')">
CalculateAverage
</button> :
<span class = "average1"></span>
</section>
javascript代码
function getNumberOfScales(){
const temp = parseInt(document.querySelector("." + parent + " .scale-count").value);
const numberOfScales = isNaN(temp) || temp<0 ? 0 : temp;
return numberOfScales;
}
function rowGenerator(index){
return `
<div class = "row" data-index = "${index}">
    Price ${index} :   <input class = "price" style = "height : 30px ; width:
50px;"
data-index = "${index}" type = "number" />   Count :  
<input class = "count" style = "height : 30px ; width: 50px;" data-index = "${index}" type
= "number" />
</div> `;
}
function handleNextButtonClick(parent){
const numberOfScales = getNumberOfScales(parent);
const formOutput = document.querySelector("."+parent+" .form-output");
let stringBuffer = " ";
for (let index=1; index<= numberOfScales; index++){
stringBuffer += rowGenerator(index);
}
formOutput.innerHTML = stringBuffer;
}
function getAverage(parent){
let sum = 0 ;
let sum_count = 0;
const numberOfScales = getNumberOfScales(parent);
for (let index = 1; index <= numberOfScales; index++){
const row_price = document.querySelector(`input.price[data-index = '${index}']`).value ;
const row_count = document.querySelector(`input.count[data-index = '${index}']`).value ;
sum += row_price * row_count;
sum_count += parseInt(row_count);
}
console.table({
sum,sum_count
})
if (sum_count ==0 ){
return 0;
} else{
return sum/sum_count ;
}
}
function handleCalculateAverageButtonClick(parent) {
const average = getAverage(parent);
const avg1 = document.querySelector("." + parent +" .average1");
avg1.innerHTML = average;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。