我正在尝试编写一个简单的银行应用程序来学习基本的 DOM 操作。这将是一个单页网站,具有大量函数调用和隐藏/显示容器。
一旦我单击主屏幕上的注册按钮,它就会调用 registerScreen()
函数,该函数然后隐藏主屏幕元素并显示一个带有文本框的表单组和一个保存填充的提交按钮在信息中。但是,一旦我打开注册屏幕,saveCustomer()
函数就会调用自身。显然,它提交了一个空白表单,这是一个问题。
我尝试了不同的事件监听器方法,例如 submit
、click
、getElementById().onclick
等。我不想在 HTML 上调用 saveCustomer()
函数,因为我不知道如何用这种方法传递信息。
function registerScreen() {
document.getElementById("welcome-container").style.display = "none";
document.getElementById("registerScreen").style.display = "block";
let customerFirstName = document.getElementById('firstName').value;
let customerLastName = document.getElementById('lastName').value;
let customerPassword = document.getElementById('password').value;
let randomID = document.getElementById("randomID");
let ID = Math.floor((Math.random() * 999) + 100);
randomID.innerHTML += ID;
//This is the line I am having problems with
document.getElementById("submitInfo").addEventListener("click", saveCustomer(ID, customerFirstName, customerLastName, customerPassword));
}
function saveCustomer (ID, customerFirstName, customerLastName, customerPassword) {
let customer = {
id: ID,
firstname: customerFirstName,
lastname: customerLastName,
password: customerPassword,
cashAmount: 0,
}
if (localStorage.getItem("customers") === null) {
let customers = [];
customers.push(customer);
localStorage.setItem("customers", JSON.stringify(customers));
} else {
let customers = JSON.parse(localStorage.getItem("customers"));
customers.push(customer);
localStorage.setItem("customers", JSON.stringify(customers));
}
alert("Registration successful.");
}
最佳答案
尝试将 saveCustomer 包装在匿名回调函数中,如下所示:
document.getElementById("submitInfo").addEventListener("click", () => {saveCustomer(ID, customerFirstName, customerLastName, customerPassword)});
关于javascript - 提交按钮无需点击即可调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54600785/