jQuery 事件 - submit() 方法 概述
jQuery 2022-06-01 12:11:5611小码哥的IT人生shichen
jQuery 事件 - submit() 方法
实例
当提交表单时,显示警告框:
$("form").submit(function(e){ alert("Submitted"); });
完整实例:
<html> <head> <script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(e){ alert("Submitted"); }); }); </script> </head> <body> <form name="input" action="" method="get"> First name: <input type="text" name="FirstName" value="Mickey" size="20"> <br />Last name: <input type="text" name="LastName" value="Mouse" size="20"> <br /> <input type="submit" value="Submit"> </form> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
定义和用法
当提交表单时,会发生 submit 事件。
该事件只适用于表单元素。
submit() 方法触发 submit 事件,或规定当发生 submit 事件时运行的函数。
触发 submit 事件
语法
$(selector).submit()
完整实例:
<html> <head> <script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(e){ alert("Submitted"); }); $("button").click(function(){ $("form").submit(); }); }); </script> </head> <body> <form name="input" action="" method="get"> First name: <input type="text" name="FirstName" value="Mickey" size="20"> <br />Last name: <input type="text" name="LastName" value="Mouse" size="20"> <br /> <input type="submit" value="Submit"> </form> <button>触发表单域的 submit 事件</button> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
将函数绑定到 submit 事件
语法
$(selector).submit(function)
参数 | 描述 |
---|---|
function | 可选。规定当发生 submit 事件时运行的函数。 |
完整实例:
<html> <head> <script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(e){ alert("Submitted"); }); }); </script> </head> <body> <form name="input" action="" method="get"> First name: <input type="text" name="FirstName" value="Mickey" size="20"> <br />Last name: <input type="text" name="LastName" value="Mouse" size="20"> <br /> <input type="submit" value="Submit"> </form> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
亲自试一试 - 实例
完整实例【阻止提交按钮的默认 action】:
<html> <head> <script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("form").submit(function(e){ e.preventDefault(); alert("Submit prevented"); }); }); </script> </head> <body> <form name="input" action="" method="get"> First name: <input type="text" name="FirstName" value="Mickey" size="20"> <br />Last name: <input type="text" name="LastName" value="Mouse" size="20"> <br /> <input type="submit" value="Submit"> </form> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
使用 preventDefault() 函数来阻止对表单的提交。