歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> jQuery中的trigger()和preventDefault()方法

jQuery中的trigger()和preventDefault()方法

日期:2017/3/1 9:37:26   编辑:Linux編程

jQuery中的trigger()和preventDefault()方法

trigger()方法用戶模擬用戶操作,比較常見的一種情況就是輸入框自動獲得焦點:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.js"></script>
<title>jquery</title>
</head>

<body>
<form name="login">
<input type="text" id="username"><br/>
<input type="password" id="pwd"><br/>
<input type="submit" value="登陸">
</form>
</body>
<script type="text/javascript">
$("form[name=login] :input[id=username]").trigger("focus");
</script>
</html>

當用戶打開這個界面的時候,用戶名輸入框就會自動得到焦點,所以用戶就可以直接輸入數據。

preventDefault()方法用戶阻止元素的默認的行為,比如說:點擊超鏈接的跳轉的行為,點擊提交按鈕表單頁面跳轉的行為。

return false; 也有阻止元素默認行為的功能,此外它還可以停止動畫的冒泡。

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.js"></script>
<title>jquery</title>
</head>

<body>
<a href="http://www.linuxidc.com" name="link">哇哦,這是一個超鏈接~</a>
</body>
<script type="text/javascript">
$("a[name=link]").click(function(event){
event.preventDefault();
});
</script>
</html>

使用return false;

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.js"></script>
<title>jquery</title>
</head>

<body>
<a href="http://www.linuxidc.com" name="link">哇哦,這是一個超鏈接~</a>
</body>
<script type="text/javascript">
$("a[name=link]").click(function(){
return false;
});
</script>
</html>

在進行表單驗證的時候,當用戶輸入的數據不正確的時候,表單此時就不應該跳轉,示例代碼如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.js"></script>
<title>jquery</title>
<style type="text/css">
.red{
color:red;
}
</style>
</head>

<body>
<form name="login" action="http://www.linuxidc.com">
<input type="text" id="username"><br/>
<input type="password" id="pwd"><br/>
<input type="submit" value="登陸">
</form>
</body>
<script type="text/javascript">
$("form[name=login] :submit").click(function(event){
$target = $("form[name=login] :input[id=username]");
var len = $target.val().length;
if(len < 5){
$target.parent().find("span.red").remove();
$warn = "<span class='red'>用戶名不能至少為5位</span>";
$target.after($warn);
alert(len);
event.preventDefault();
}
})

</script>
</html>

------------------------------------------分割線------------------------------------------

jQuery權威指南 PDF版中文+配套源代碼 http://www.linuxidc.com/Linux/2013-10/91059.htm

jQuery實戰 中文PDF+源碼 http://www.linuxidc.com/Linux/2013-09/90631.htm

《jQuery即學即用(雙色)》 PDF+源代碼 http://www.linuxidc.com/Linux/2013-09/90383.htm

鋒利的jQuery(第2版) 完整版PDF+源碼 http://www.linuxidc.com/Linux/2013-10/91527.htm

jQuery完成帶復選框的表格行高亮顯示 http://www.linuxidc.com/Linux/2013-08/89406.htm

jQuery基礎教程(第4版) PDF 完整高清版+配套源碼 http://www.linuxidc.com/Linux/2014-03/98162.htm

--------------------------------------分割線 --------------------------------------

jQuery 的詳細介紹:請點這裡
jQuery 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved