標籤:style blog http color io 使用 java ar for
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>
當使用者開啟這個介面的時候,username輸入框就會自己主動得到焦點,所以使用者就能夠直接輸入資料。
preventDefault()方法使用者阻止元素的預設的行為,比方說:點擊超連結的跳轉的行為,點擊提交button表單頁面跳轉的行為。
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.baidu.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.baidu.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.baidu.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中的trigger()和preventDefault()方法