DIV CSS 佈局教程網

用 jQuery 實作同時支援 IE 與 Firefox 的 Enter 鍵事件
編輯:JQuery特效代碼     

在表單中按下 Enter 就觸發確定按鈕,是很順手的使用體驗。以下這段程式碼以 jQuery 完成,同時相容 IE 與 Firefox,複製即可使用(前提是已引入 jQuery)。作者實測網上不少寫法在 Firefox 下會失效,因此特別整理這份可用版本,也歡迎大家一起指教。

完整程式碼

<script src="jquery.1.3.2.js" type="text/javascript"></script> <script type="text/javascript"> document.onkeydown = function (e) { var theEvent = window.event || e; var code = theEvent.keyCode || theEvent.which; if (code == 13) { $("#but1").click(); } } $(document).ready(function () { $("#but1").click(function () { alert("我是enter事件," + "text值:" + $("#text1").val()); }) $("#but2").click(function () { alert("我是Jquery事件" + "text值:" + $("#text1").val()); }) }); </script>

<input type="text" id="text1" /> <input type="button" id="but1" value="確定(我是enter事件)"/> <input type="submit" id="but2" value="確定(我是Jquery事件)" />

原理說明

關鍵在於 document.onkeydown 的處理:透過 window.event || e 取得事件物件,再用 keyCode || which 讀出按鍵碼,當偵測到 13(即 Enter)時,就觸發 id 為 but1 的按鈕點擊。由於同時兼顧了 IE 的 window.event 與標準瀏覽器的 e,才能在兩者下都正常運作。

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