HTML/JS代码完善:实现验证跳转、退格及输入字符限制功能
验证码输入器功能完善
针对需求,我们对代码做以下修改:
- 给验证码输入框添加
maxlength属性,限制最大输入长度为4(匹配验证码位数) - 完善
myFunction2函数:验证输入值是否为"1101",正确则跳转指定页面;错误则将输入框文字设为红色并清空内容 - 完善
myFunction3函数:实现退格功能,删除输入框最后一位字符 - 修正原代码中多个按钮重复使用同一
id的问题(ID需唯一,此处移除重复的id="field1")
完整代码
<html> <body> <p class="Header"> Code: </p> <!-- 添加maxlength限制输入长度 --> <input type="text" id="field2" class="field2" maxlength="4"><br><br> <div class="Tasten"> <input class="calculator" type="button" value=1 onclick="myFunction(this)"> <input class="calculator" type="button" value=2 onclick="myFunction(this)"> <input class="calculator" type="button" value=3 onclick="myFunction(this)"><br> <input class="calculator" type="button" value=4 onclick="myFunction(this)"> <input class="calculator" type="button" value=5 onclick="myFunction(this)"> <input class="calculator" type="button" value=6 onclick="myFunction(this)"><br> <input class="calculator" type="button" value=7 onclick="myFunction(this)"> <input class="calculator" type="button" value=8 onclick="myFunction(this)"> <input class="calculator" type="button" value=9 onclick="myFunction(this)"><br> <input class="calculator0" type="button" value="0" onclick="myFunction(this)"> </div> <input class="Back" type="button" id="OK" value="<-" onclick="myFunction3()"> <input class="Enter" type="button" id="OK" value="OK" onclick="myFunction2()"> <script> function myFunction(button) { document.getElementById("field2").value += button.value; } function myFunction2() { const input = document.getElementById("field2"); // 注意input.value是字符串,需与"1101"比较 if (input.value === "1101"){ // 替换为你要跳转的URL window.location.href = "指定页面地址"; } else { input.style.color = "red"; input.value = ""; // 可选:3秒后恢复默认文字颜色 setTimeout(() => { input.style.color = ""; }, 3000); } } function myFunction3(){ const input = document.getElementById("field2"); // 截取除最后一位外的所有字符 input.value = input.value.slice(0, -1); } </script> </body> </html>
关键说明
maxlength="4"确保输入框最多只能输入4位字符,符合验证码长度需求myFunction2中使用字符串比较"1101",因为输入框的value属性始终是字符串类型- 退格功能通过
slice(0, -1)实现,该方法会返回原字符串从开头到倒数第二位的子串 - 可选添加了定时器恢复输入框文字颜色,避免错误提示长期停留
内容的提问来源于stack exchange,提问作者Bene
相关产品推荐
相关产品推荐

