DIV CSS 佈局教程網

jQuery 實現按回車提交數據的代碼示例
編輯:JQuery特效代碼     

讓用戶按下回車鍵就能提交表單,是一個能顯著提升操作體驗的小功能。其實實現起來很簡單:只要監聽到回車鍵,就觸發綁定好的提交事件即可。

核心思路

我們在目標控件上綁定 keydown 事件,判斷按下的鍵是否為回車(鍵值 13),若是則觸發按鈕的 click 事件,而按鈕上已經綁定了 ajax 提交表單的邏輯。

$(document).ready(function(){
$("按下回車的控件").keydown(function(e){
var curKey = e.which;
if(curKey == 13){
$("#回車事件按鈕控件").click();
return false;
}
});
});

兼容原生 JS 的寫法

也可以直接在 document 上監聽鍵盤事件,同時兼容不同瀏覽器:

document.onkeydown = function (e) {
var theEvent = window.event || e;
var code = theEvent.keyCode || theEvent.which;
if (code == 13) { $("#login_submit").click(); }
}

結合 Ajax 的登錄示例

$(document).ready(function() {
  $("#login_submit").bind('click',function(){
    var username=$("#username").val();
    var password=$("#password").val();
    $.ajax({
       type : 'POST',
       url : './login.php',
       data: {type :'ajax',username:username,password:password},
       success : function(msg){
           if(msg==-1){ alert('用戶名不能為空'); $("#username").focus(); }
           if(msg==-2){ alert('用戶名不存在'); $("#username").val(""); $("#username").focus(); }
           if(msg==-3){ alert('密碼不能為空'); $("#password").focus(); }
           if(msg==-6){ alert('密碼輸入不正確'); $("#password").focus(); }
           if(msg==1){ window.location.href='./index.php'; }
       }
    });
  });
});

透過返回不同的狀態碼,前端可以給出對應的提示並引導用戶,形成完整的登錄交互流程。

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