时间:2022-09-30 09:28:55 | 栏目:JavaScript代码 | 点击:次
e.preventDefault()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div { width: 600px; height: 600px; margin: 50px auto; background-color: skyblue; padding: 20px; } div input { width: 520px; height: 50px; margin-top: 50px; } </style> </head> <body> <div> <form action=""> <input type="text" name="name" placeholder="输入用户名"><br> <p class="nameTip"></p> <input type="password" name="password" placeholder="输入密码"><br> <p class="passwordTip"></p> <input type="submit" name="submit" value="按钮"> </form> </div> <script> var formEle = document.querySelector('form') var nameinput = document.querySelector('input[name="name"]') var passwordinput = document.querySelector('input[name="password"]') var pnameTip = document.querySelector('.nameTip') var ppasswordTip = document.querySelector('.passwordTip') //是否为空判定 function checkUserNameNull(){ if(nameinput.value==''){ pnameTip.innerHTML='输入名字' return false }else{ pnameTip.innerHTML='' return true } } //失去焦点进行用户名是否为空验证 nameinput.οnblur=function (){ checkUserNameNull() } //是否为空判定 function checkPasswordNull(){ if(passwordinput.value==''){ ppasswordTip.innerHTML='输入名字' return false }else{ ppasswordTip.innerHTML='' return true } } //失去焦点进行密码框是否为空验证 passwordinput.οnblur=function (){ checkPasswordNull() } //提交时验证 formEle.onsubmit = function (e) { e.preventDefault() //阻止表单默认提交 var nameisok=checkUserNameNull() var passwordisok= checkPasswordNull() //都满足不为空提交 if(nameisok && passwordisok){ location.href = 'https://www.baidu.com/' } } //键值提交 document.οnkeyup=function (e){ var keyCode=e.keyCode|| e.which if(keyCode==13&&e.shiftKey){ var nameisok=checkUserNameNull() var passwordisok= checkPasswordNull() if(nameisok && passwordisok){ location.href = 'https://www.baidu.com/' } } } </script> </body> </html>