<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> new document </title> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /> <style type="text/css"></style> <script type="text/javascript"> //實(shí)例:submit按鈕,結(jié)合onsubmit事件,驗(yàn)證和提交表單 function checkForm(){ //判斷用戶名和密碼是否為空 if(document.form1.username.value==""){ window.alert("用戶名不能為空"); return false; }else if(document.form1.username.value.length<5 ||
document.form1.username.value.length>20){ window.alert("用戶名在5-20位"); return false; }else if(document.form1.userpwd.value==""){ window.alert("密碼不能為空"); return false; }else if(document.form1.userpwd.value.length<5 ||
document.form1.userpwd.value.length>20){ window.alert("密碼必須在5-20位"); return false; } } </script> </head> <body> <form name="form1" method="get" action="login.php" onsubmit="return checkForm()"> 用戶名:<input type="text" name="username" /> 密碼:<input type="password" name="userpwd" /> <input type="submit" value="提交表單" /> </form> //單機(jī)以下的鏈接,不會(huì)跳轉(zhuǎn)網(wǎng)址,因?yàn)槟J(rèn)動(dòng)作被阻止了 <a href="http://www.itcast.cn" onclick="return false">北京交通網(wǎng)</a> </body> </html>
onsubmit="return checkForm()" 加return是事件返回事件,當(dāng)返回值為false的時(shí)候會(huì)阻止表單提交。
事件返回值:
事件的返回值,會(huì)影響事件的默認(rèn)動(dòng)作。
如果事件的返回值為false,則阻止默認(rèn)動(dòng)作執(zhí)行。
如果事件返回值為ture或空,則默認(rèn)動(dòng)作執(zhí)行。
如果事件沒有任何返回值,則默認(rèn)動(dòng)作執(zhí)行。
受影響的事件有兩個(gè):onclick、onsubmit
其他事件的返回值,不會(huì)影響默認(rèn)動(dòng)作。
onclick的返回值也會(huì)組織submit的提交。
【 微信掃一掃 】