DIV CSS 佈局教程網

jQuery 綁定 click 事件的 3 種寫法對比
編輯:JavaScript綜合知識     

使用 jQuery 為元素綁定點擊事件,是日常開發中最頻繁的操作之一。本文用簡潔的代碼示例,梳理 jQuery 中綁定 click 事件的三種常見寫法,方便你直接複製使用。

第一種方式:使用 click() 方法:

? 1 2 3 4 $(document).ready(function(){ $("#clickme").click(function(){ alert("Hello World click"); });

第二種方式:使用 bind() 方法:

? 1 2 3 $('#clickmebind').bind("click", function(){ alert("Hello World bind"); });

第三種方式:使用 on() 方法:

? 1 2 3 4 $('#clickmeon').on('click', function(){ alert("Hello World on"); }); });

需要特別注意:第三種 on() 方式只適用於 jQuery 1.7 及以上版本。完整源碼如下:

? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />   <script type="text/javascript" src="js/jquery-1.6.1.min.js"></script> <script type="text/javascript" src="js/jquery.validate.js"></script> <script type="text/javascript" src="js/jquery.metadata.js"></script> <script type="text/javascript" src="js/messages_zh.js"></script> <style type="text/css"> #frm label.error { color: Red; } </style> </head> <script type="text/javascript">   $(document).ready(function(){ $("#clickme").click(function(){ alert("Hello World click"); });     $('#clickmebind').bind("click", function(){ alert("Hello World bind"); });   $('#clickmeon').on('click', function(){ alert("Hello World on"); }); });   </script> <body> <label></label> <form id="frm" name="frm" method="post" action=""><label>用 戶 名: <input type="text" name="username" id="username" /> </label> <p> <label>郵 編 :<label></label></label> <label> <input type="text" name="postcode" id="postcode" /> <br /> </label> </p> <p><label>數 字 : <input type="text" name="number" id="number" /> </label> <br /><label>身份證號: <input type="text" name="identifier" id="identifier" /> </label>   <label> <input type="button" name="clickme" id="clickme" value="click me" /> </label> <label> <input type="button" name="clickmebind" id="clickmebind" value="clickme_bind" /> </label> <label> <input type="button" name="clickmeon" id="clickmeon" value="clickme_on" /> </label> </p> </form> </body>

實踐建議:新項目中推薦使用 on(),它不僅語法現代,還支持事件代理,能輕鬆處理動態生成的元素,是目前的官方推薦做法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved