首页 / 操作系统 / Linux / jQuery中的trigger()和preventDefault()方法
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.htmjQuery实战 中文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.htmjQuery完成带复选框的表格行高亮显示 http://www.linuxidc.com/Linux/2013-08/89406.htmjQuery基础教程(第4版) PDF 完整高清版+配套源码 http://www.linuxidc.com/Linux/2014-03/98162.htm--------------------------------------分割线 --------------------------------------jQuery 的详细介绍:请点这里
jQuery 的下载地址:请点这里本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-11/109186.htm