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

來源:互聯網
上載者:User

標籤: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()方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.