我正在在线上学习制作贷款计算器的教程。计算器可以正常工作,但是当您在变量之一中输入零或负数(您不能有负/零贷款额,利率或年数)时,我试图放置一个错误窗口。我希望能够在特定的错误窗口中说:当在贷款金额中输入零或负数时,您不能输入零或负数作为贷款金额的值。对于其他变量,如果可以的话,可以在其中输入值。 当您打开显示“您不能放置任何负数或零”的计算器时,我能够制作一个错误窗口,并且在您输入零或负数时都会弹出该错误窗口。我试图调用每个变量的const并弹出窗口,但这没用。
document.getElementById("loan-form").addEventListener("submit", computeResults);
function computeResults(e) {
// UI
const UIamount = document.getElementById("amount").value;
const UIinterest = document.getElementById("interest").value;
const UIyears = document.getElementById("years").value;
hola(UIamount);
hola(UIinterest);
hola(UIyears);
// Calculate
const principal = parseFloat(UIamount);
const CalculateInterest = parseFloat(UIinterest) / 100 / 12;
const calculatedPayments = parseFloat(UIyears) * 12;
//Compute monthly Payment
const x = Math.pow(1 + CalculateInterest, calculatedPayments);
const monthly = (principal * x * CalculateInterest) / (x - 1);
const monthlyPayment = monthly.toFixed(2);
//Compute Interest
const totalInterest = (monthly *calculatedPayments - principal).toFixed(2);
//Compute Total Payment
const totalPayment = (monthly * calculatedPayments).toFixed(2);
//Show results
document.getElementById("monthlyPayment").innerHTML = "$" + monthlyPayment;
document.getElementById("totalInterest").innerHTML = "%" + totalInterest;
document.getElementById("totalPayment").innerHTML = "$" + totalPayment;
e.preventDefault();
}
function hola(x) {
console.log(x);
if(x == 0) {
document.getElementById("cont1").style.display="none";
}
if(x == 1) {
document.getElementById("cont1").style.display="none";
}
if(x<=0) {
document.getElementById("cont1").style.display="block";
}
}
答案 0 :(得分:0)
您的代码将遇到的一个问题是,如果一个值无效,但该值下的其他值有效,则错误将被隐藏。
使用if语句代替函数:
const UIamount = document.getElementById("amount").value;
const UIinterest = document.getElementById("interest").value;
const UIyears = document.getElementById("years").value;
let err_box = document.getElementById("cont1");
err_box.style.display="none";//hide the popup first
if(UIamount <= 0 || UIinterest <= 0 || UIyears <= 0){
err_box.style.display="block";
}