我正在尝试在JS中创建一个采用低温和高温的表单并创建一个看起来
的输出如下图所示:
我一直遇到的问题是,当我第二次点击提交时,它会重复两次。因此,如果我第一次输入30,40,第二次输入60,80。它会显示:
30,40
30,40
60,80
当您输入更多数据时,问题会变得更糟。
'use strict';
// Reference to where the output goes:
var output = document.getElementById('output');
// Create a new object:
var todays_date = new Date();
var day = todays_date.getDate();
var month = todays_date.getMonth() + 1;
var year = todays_date.getFullYear();
var temps_data_low = [];
var temps_data_high = [];
var temp_data_msg = "";
var sum_low = 0;
var sum_high = 0;
temp_data_msg += "Date" + ' ' + "Low Temperature" + ' ' + "High Temperature" + '<br>';
function call() {
'use strict';
var LowTemperature = parseFloat(document.getElementById('LowTemperature').value);
var HighTemperature = parseFloat(document.getElementById('HighTemperature').value);
console.log(LowTemperature);
console.log(HighTemperature);
temps_data_low.push(LowTemperature);
temps_data_high.push(HighTemperature);
// Update the page:
for (var i = 0, count = temps_data_low.length; i < count; i++) {
if (temps_data_low.length > 1){
day = day - 1;
}
sum_low += temps_data_low[i];
sum_high += temps_data_high[i];
temp_data_msg += month + "/" + day + "/" + year + ' ' + temps_data_low[i] + " " + temps_data_high[i] + "<br>";
}
calc(LowTemperature,HighTemperature,temp_data_msg,temps_data_low,temps_data_high,sum_low,sum_high);
}
function calc(LowTemperature,HighTemperature,temp_data_msg,temps_data_low,temps_data_high,sum_low,sum_high) {
'use strict';
if (temps_data_low.length === 1) {
temp_data_msg += "Averages " + LowTemperature + " " + HighTemperature + "<br>";
}
else {
temp_data_msg += "Averages " + (sum_low/temps_data_low.length) + " " + (sum_high/temps_data_high.length) + "<br>";
}
// Display the messsage
output.innerHTML = temp_data_msg;
return false;
}
// Initial setup:
function init() {
'use strict';
document.getElementById('theForm').onsubmit = call;
} // End of init() function.
window.onload = init;
答案 0 :(得分:1)
您永远不会重置temp_data_msg
变量。
因此,每次提交表单时,您都会将所有相同的数据附加到上一个输出中。
您可以在temp_data_msg = '';
函数的for
循环之前添加call
来解决此问题:
function call() {
//omitted...
temps_data_low.push(LowTemperature);
temps_data_high.push(HighTemperature);
temp_data_msg = ''; //<----- this line
// Update the page:
for (var i = 0, count = temps_data_low.length; i < count; i++) {
//omitted...
这会产生破坏标题的副作用,因此在您声明temp_data_msg
的脚本顶部我将其更改为
var temp_data_header = "Date" + ' ' + "Low Temperature" + ' ' + "High Temperature" + '<br>';
然后输出最终文本时:
output.innerHTML = temp_data_header + temp_data_msg;