jQuery中的阻止默认行为

在很多元素中都存在默认行为,例如表单中的submit按钮,a标签等等。如果想要消除其中的默认行为,就需要一个事件event的方法来消除他们的默认行为。

这个方法就是event.preventDefault();演示方法如下:

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
 2 "http://www.w3.org/TR/html4/strict.dtd">
 3 
 4 <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
 5     <head>
 6         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 7         <title>阻止默认行为的演示</title>
 8         <meta name="author" content="Administrator" />
 9         <script src="script/jquery-1.12.2.js" type="text/javascript"></script>
10         <!-- Date: 2016-03-26 -->
11     </head>
12     <body>
13         <script type="text/javascript">
14             $(function() {
15                 $("#sub").bind("click", function(event) {
16                     var username = $("#username").val();
17                     if (username == "") {
18                         $("#msg").html("<p>文本框的值不能为空!</p>");
19                         event.preventDefault();
20                     }
21                 });
22             });
23         </script>
24         <form action="test.html">
25             用户名:
26             <input type="text" id="username" />
27             <input type="submit" value="提交" id="sub" />
28         </form>
29         <div id="msg"></div>
30     </body>
31 </html>

 

posted @ 2016-03-26 16:26  Arther_J  阅读(980)  评论(0编辑  收藏  举报