JS表單提交中onsubmit事件return的作用詳解
JS表單提交中onsubmit事件return的作用
1.html
<!DOCTYPE?html> <html> <head> <title>JS表單提交中onsubmit事件return的作用</title> </head> <body> <form method="post"?action="2.html"?onsubmit="return?Checkname()"> <input?id="name"?type="text"?placeholder="請輸入你的名字"> <button>提交</button> </form> </body> </html> <script?type="text/javascript"> ????function?Checkname()?{ ????????var?name=document.getElementById('name').value; ????????if?(!name)?{ ????????????alert('名字為空'); ????????????return?false; ????????}else{ ????????????return?true; ????????} ????} </script>
2.html
<!DOCTYPE?html> <html> <head> <title>JS表單提交中onsubmit事件return的作用</title> </head> <body> ????恭喜表單提交成功 </body> </html>
代碼運行效果圖
1.不填寫名字
2.填寫名字
代碼分析
當點擊提交按鈕(button按鈕)的時候,瀏覽器會自動觸發(fā)onsubmit事件,執(zhí)行Checkname()函數。Checkname()函數通過判斷名字是否存在,來返回true或者false。
當Checkname()返回false的時候,onsubmit事件可以看成為:
onsubmit="return?false"
當Checkname()返回true的時候,onsubmit事件可以看成為:
onsubmit="return?true"
重點
此時onsubmit中return的作用就是將Checkname()函數運行返回的結果(true或者false),再向上返回(返回給瀏覽器)。瀏覽器如果接收到onsubmit返回的是false,則阻止表單提交。反之,如果接收到的是true,表單就會提交到action屬性指向的2.html頁面。
以上就是JS表單提交中onsubmit事件return的作用詳解的詳細內容,更多關于JS表單提交onsubmit事件return的資料請關注腳本之家其它相關文章!