DOM操作问题:表单提交时变量未更新,如何传递最新值?
解决银行APP注册时输入值为空的问题
你的问题核心很明确:你在调用registerScreen()的时候就立刻获取了输入框的值,但这时候用户还没填写任何内容,所以这些变量一直是空的,后续点击提交时自然传递的是空值。要解决这个问题,只需要把获取输入值的逻辑移到提交按钮的点击回调里,这样每次用户点击提交时,才会去读取输入框的最新内容。
另外我还发现代码里有两个小问题,一起帮你修正了:
修正后的完整代码:
function registerScreen() { document.getElementById("welcome-container").style.display = "none"; document.getElementById("registerScreen").style.display = "block"; // 先生成随机ID,这个可以保留在外面,因为不需要依赖用户输入 let customerId = Math.floor((Math.random() * 999) + 100); document.getElementById("randomID").innerHTML += customerId; // 点击提交时才去获取最新的输入值 document.getElementById("submitInfo").addEventListener("click", (e) => { // 在这里获取输入框的当前值 let customerFirstName = document.getElementById('firstName').value; let customerLastName = document.getElementById('lastName').value; let customerPassword = document.getElementById('password').value; // 传递事件对象e,用于阻止默认行为 saveCustomer(e, customerId, customerFirstName, customerLastName, customerPassword); }); } function saveCustomer(e, customerId, customerFirstName, customerLastName, customerPassword) { let customer = { id: customerId, firstname: customerFirstName, lastname: customerLastName, password: customerPassword, cashAmount: 0, }; if (!validateForm(customerFirstName, customerLastName, customerPassword)) { return false; } 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)); } document.getElementById('registerInfo').reset(); e.preventDefault(); // 现在e参数存在了,可以正常调用 alert("Registration successful."); } function validateForm(customerFirstName, customerLastName, customerPassword) { if (!customerFirstName || !customerLastName || !customerPassword) { alert('Please fill in the form'); return false; } // 修正正则表达式的变量名错误 var regularExpression = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/; var regex = new RegExp(regularExpression); // 之前用了未定义的expression,现在改成regularExpression if (!customerPassword.match(regex)) { alert('Please use a valid password'); return false; } return true; }
关键修改点说明:
把输入值的获取移到点击回调内:
原来的代码在registerScreen()执行时就获取了输入框的值,这时候用户还没填写,所以customerFirstName等变量都是空字符串。移到点击事件里后,每次用户点击提交,都会实时读取输入框的最新内容。修正
saveCustomer的事件参数:
你原来的代码里用了e.preventDefault()但没有传递e参数,现在在点击回调里把e传给saveCustomer,这样就能正常阻止表单默认提交行为了。修复正则表达式的变量错误:
validateForm里定义了regularExpression但用了未声明的expression,导致正则验证失效,现在修正为正确的变量名。
这样修改后,就能确保提交时传递的是用户输入的最新值,同时解决了其他潜在的小问题。
内容的提问来源于stack exchange,提问作者Özenç B.




