preventDefault()方法用来阻止元素的默认行为,如单击超链接会跳转,单击‘提交’按钮后表单会提交等。
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>preventDefault()</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var username = $("#username").val();
$("#sub").bind("click",function(event){
if( username == ""){
$("#msg").html("<p>文本框的值不能为空</p>");
event.preventDefault();
}
});
})
</script>
<style type="text/css">
</style>
</head>
<body>
<form action="text.html">
用户名:<input type="text" id="username"/>
<input type="submit" value="提交" id="sub"/>
</form>
<div id="msg"></div>
</body>
</html>