2014-01-17 30 views
0

我只能夠得到一個按鈕,通過建立2個獨立事件的工作原理:按鈕與可以單擊或按下Enter鍵

$('#loginSubmit').click (function() 
{ 
      var userName = $('#userName').val(); 
      var password = $('#password').val(); 
          event.preventDefault(); 
          $.ajax({ 
              type: "POST", 
              url: "auth.php", 
              data:"userName="+userName+"&password="+password, 
              success: function(result) 
              { 
                //$('#mainBody').html(result); 
                window.location.replace('chooseGroup.php'); 
              } 
            }) 
}); 


$('input').keypress(function(event) 
{ 
    if (event.which == 13) { 

      var userName = $('#userName').val(); 
      var password = $('#password').val(); 
          event.preventDefault(); 
          $.ajax({ 
              type: "POST", 
              url: "auth.php", 
              data: "userName="+userName+"&password="+password, 
              success: function(result) 
              { 
                //$('#mainBody').html(result); 
                window.location.replace('chooseGroup.php'); 
              } 
            }) 
        } 
    }) 
    }); 

HTML:

<div class='Lrow'><input type='button' id='loginSubmit' value='Login'></div> 

我知道有可能是一個更好的方法。我愛聽到它。無論如何,如果我使用mozilla瀏覽器,在按鍵功能中「事件」是不確定的。這在鉻中工作正常。有什麼想法嗎?

+1

'type =「submit」'而不是'type =「button」'? – Krishna

+0

這實際上是一種形式嗎?爲什麼不處理表單的'submit'事件而不是按鈕的'click'? – Mathletics

+0

@Krishna會提交幫助來調用ajax調用? – Miller

回答

4

將公共代碼放入函數中。

var mySubmitFunction (event) { 
    //the code 
} 

$('#loginSubmit').on("click", mySubmitFunction); 
$('input').keypress(function(event){ 
    if (event.which == 13) { 
     mySubmitFunction(event); 
    } 
}); 

但不聽點擊一個更好的方式/確定鍵。更好的方法是讓表單按照自己的意願去做。

表單將在您輸入正確時提交。您只需添加一個提交按鈕和一個提交事件。您取消提交,並進行Ajax調用。設置按鈕類型提交,它應該工作。獎金是如果JS被禁用,表單仍然提交給服務器。

$("#YourForm").on("submit", function(event){ /* code here */ }); 
+0

似乎更加整齊,然後我有,我將使用。謝謝。然而,這是如何處理新聞輸入事件? – bart2puck

+0

哎呀。你只是編輯。我看看 – bart2puck

+0

你走了。處理按鈕而不是表單本身幾乎總是錯誤的方法。 – Mathletics

0

把你的代碼中的功能,例如:ajaxSubmit()然後使用jquery on打電話給你的功能

function ajaxSubmit(){ 
    var userName = $('#userName').val(); 
    var password = $('#password').val(); 
    event.preventDefault(); 
    $.ajax({ 
     type: "POST", 
     url: "auth.php", 
     data: "userName="+userName+"&password="+password, 
     success: function(result){ 
      //$('#mainBody').html(result); 
      window.location.replace('chooseGroup.php'); 
     } 
    }); 
} 

$('#loginSubmit').on("click", ajaxSubmit); 

$('#loginSubmit').on("click", function(event){ 
    if (event.which == 13) { 
     ajaxSubmit(event); 
    } 
}); 
0

在方法需要一個或多個PARAMS作爲事件名稱如下:

$('#loginSubmit').on("click keypress", function(event){ 

    if (event.type == "keypress") { 
    if(event.which == 13) 
    { 
     put your code here or call function 
    } 
    } 
else//click event 
    { 
     put your code here or call function 
    } 

}); 
相關問題