文本框二次输入值未更新,如何通过同一按钮获取多组输入值?
问题解决:同一输入框多次点击获取独立值
你的代码问题出在嵌套绑定点击事件上——第一次点击按钮时,你又给按钮加了新的点击监听,导致后续点击会同时触发新旧两层事件逻辑,状态混乱,所以第二次获取的还是首次输入的值。
解决思路是用一个状态变量跟踪当前输入步骤,只绑定一次点击事件,在事件内部根据当前步骤处理对应逻辑:
修正后的完整代码
HTML(修正了head的位置错误)
<!DOCTYPE html> <html> <head> <link rel="stylesheet" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> </head> <body> <div id="content"> <h1></h1> <input id="inputField"> <button id="submit">Submit</button> </div> <script src="app.js"></script> </body> </html>
CSS(无需改动)
body { min-height: 100vh; } * { margin: 0; padding: 0; box-sizing: border-box; }
JavaScript(核心改动)
$(document).ready(function(){ let firstInput; let secondInput; let h1 = document.querySelector('h1'); // 用step变量跟踪当前输入步骤:1=输入问题数,2=输入每题答案数,3=完成 let step = 1; h1.textContent = 'Enter the number of questions:'; // 只绑定一次点击事件 $("#submit").click(function(){ const inputVal = document.getElementById('inputField').value; // 先校验输入有效性 if(checkValid(inputVal)){ alert(step === 1 ? 'No.1 invalid, try again :)' : 'No.2 invalid, try again :)'); return; } // 根据当前步骤处理逻辑 if(step === 1){ firstInput = inputVal; console.log('First input: ' + firstInput); h1.textContent = 'Enter the number of answers per question:'; // 清空输入框,准备下一次输入 document.getElementById('inputField').value = ''; step = 2; } else if(step === 2){ secondInput = inputVal; console.log('Second input: ' + secondInput); h1.textContent = 'Done'; // 清空输入框 document.getElementById('inputField').value = ''; step = 3; console.log('Combined: ', firstInput, secondInput); } }) function checkValid(inputValue){ return inputValue.length>2 || isNaN(inputValue[0]) || parseInt(inputValue)===0 || parseInt(inputValue)>50; } })
关键改动说明
- 新增
step变量明确当前输入阶段,避免嵌套事件的混乱 - 只给按钮绑定一次点击事件,所有逻辑在同一个事件处理函数内完成
- 每次完成当前步骤后更新
step并清空输入框,引导用户输入下一组值 - 移除了冗余的
updateInputValue函数,直接操作输入框值更简洁
内容的提问来源于stack exchange,提问作者MyNameIsJeff
相关产品推荐
相关产品推荐

