用户输入输入,单击按钮,并调用函数以执行某些计算。如果字段的类型或值不正确,则会显示错误消息。如果其中一个字段错误,则该字段需要显示错误消息。如果多个字段错误,则这些字段需要显示错误消息。现在,如果字段错误,页面只显示一条错误消息,即使所有字段都是错误的。我确信这是一个简单的解决办法,但我一直在撞墙。有什么建议?谢谢!以下是代码的适用部分:
if (isNaN(theMilesDriven) || theMilesDriven <= 0) {
theMilesDrivenError.firstChild.nodeValue = "Please enter a number greater than 0 for the miles driven.";
return false;
}
if (isNaN(theGallonsUsed) || theGallonsUsed <= 0) {
theGallonsUsedError.firstChild.nodeValue = "Please enter a number greater than 0 for the gallons of gas used.";
return false;
}
if (isNaN(thePriceGallon) || thePriceGallon <= 0) {
thePriceGallonError.firstChild.nodeValue = "Please enter a number greater than 0 for the price per gallon.";
return false;
}
答案 0 :(得分:0)
这就是我所做的似乎可以解决问题的方法:
//Verify the input is numerical and greater than 0
if (isNaN(theMilesDriven) || theMilesDriven <= 0) {
theMilesDrivenError.firstChild.nodeValue = "Please enter a number greater than 0 for the miles driven.";
}
if (isNaN(theGallonsUsed) || theGallonsUsed <= 0) {
theGallonsUsedError.firstChild.nodeValue = "Please enter a number greater than 0 for the gallons of gas used.";
}
if (isNaN(thePriceGallon) || thePriceGallon <= 0) {
thePriceGallonError.firstChild.nodeValue = "Please enter a number greater than 0 for the price per gallon.";
}
else {
//Perform the calculations and write the results to the page
var milesPerGallon = theMilesDriven / theGallonsUsed;
var theMPG = document.getElementById("mpg");
theMPG.firstChild.nodeValue = "Your MPG is: " + milesPerGallon.toFixed(2);
var cost = theGallonsUsed * thePriceGallon;
var theCost = document.getElementById("cost");
theCost.firstChild.nodeValue = "Your cost for this trip is: $" + cost.toFixed(2);
}
答案 1 :(得分:0)
如果找到前两个错误之一,您的解决方案仍将进行计算。这是另一种选择:
var isErrorFound = false;
if (isNaN(theMilesDriven) || theMilesDriven <= 0) {
theMilesDrivenError.firstChild.nodeValue = "Please enter a number greater than 0 for the miles driven.";
isErrorFound = true;
}
if (isNaN(theGallonsUsed) || theGallonsUsed <= 0) {
theGallonsUsedError.firstChild.nodeValue = "Please enter a number greater than 0 for the gallons of gas used.";
isErrorFound = true;
}
if (isNaN(thePriceGallon) || thePriceGallon <= 0) {
thePriceGallonError.firstChild.nodeValue = "Please enter a number greater than 0 for the price per gallon.";
isErrorFound = true;
}
if (!isErrorFound) {
//Perform the calculations and write the results to the page
var milesPerGallon = theMilesDriven / theGallonsUsed;
var theMPG = document.getElementById("mpg");
theMPG.firstChild.nodeValue = "Your MPG is: " + milesPerGallon.toFixed(2);
var cost = theGallonsUsed * thePriceGallon;
var theCost = document.getElementById("cost");
theCost.firstChild.nodeValue = "Your cost for this trip is: $" + cost.toFixed(2);
}