2010-12-05 105 views
3

我想捕捉回車鍵使按鍵點擊捕獲回車鍵使按鍵點擊使用JavaScript

我有此javascript:

function doClick(buttonName,e) 
    { 
     //the purpose of this function is to allow the enter key to 
     //point to the correct button to click. 
     var key; 

     if(window.event) 
       key = window.event.keyCode;  //IE 
     else 
       key = e.which;  //firefox 

     if (key == 13) 
     { 
      //Get the button the user wants to have clicked 
      var btn = document.getElementById('submit'); 
      if (btn != null) 
      { //If we find the button click it 
       btn.click(); 
       event.keyCode = 0 
      } 
     } 
    } 

與HTML

<input type="button" id="submit" value="Search" onClick="doSomeThing();" /> 
<input type="text" name="search" onKeyPress="doClick('submit',event)" /> 

這是工作正常的IE瀏覽器,但它沒有與Firefox,

爲什麼?任何人都可以修復這個JavaScript代碼在所有瀏覽器上工作。

謝謝

+0

你能解釋發生了什麼?該方法是否被調用? – cwallenpoole 2010-12-05 12:11:42

+0

是的。謝謝 – Swell 2010-12-05 12:48:59

+0

此鏈接將幫助你明確 http://stackoverflow.com/questions/155188/trigger-a-button-click-with-javascript-on-the-enter-key-in-a-text-box – 2012-08-16 07:02:35

回答

7

你真的應該不使用內聯事件處理程序:

window.onload = function() { 
    document.getElementById('submit').onclick = doSomething; 
    document.getElementById('search').onkeypress = function(e) { 
     doClick('submit', e); 
    }; 
}; 

function doClick(buttonName,e) 
{ 
    //the purpose of this function is to allow the enter key to 
    //point to the correct button to click. 
    var ev = e || window.event; 
    var key = ev.keyCode; 

    if (key == 13) 
    { 
    //Get the button the user wants to have clicked 
    var btn = document.getElementById(buttonName); 
    if (btn != null) 
    { 
     //If we find the button click it 
     btn.click(); 
     ev.preventDefault(); 
    } 
    } 
} 

那麼你的HTML應該是這樣的:

<input type="button" id="submit" value="Search"/> 
<input type="text" name="search" id="search" /> 
+2

OP使用事件處理程序屬性的事實與問題無關,並聲稱OP不應該這樣做是教條式的。使用事件處理程序屬性並且不引入功能問題是完全有效的。 – 2010-12-05 11:49:58

2

爲什麼不使用像jQuery的包裝JS框架?它爲你做了所有的跨瀏覽器的東西。只是把我的頭頂部,這可能是工作(當然,你應該確認):

jQuery(function(){ 
    jQuery(window).keyup(function(e){ 
    if (e.keyCode == 13) { 
     // handle click logic here 
    } 
    }); 
}); 
5

我建議使用​​事件,而不是針對這種特殊情況,因爲它簡化了按鍵檢測:你可以使用keyCode在所有瀏覽器中。此外,你正在傳遞你想要點擊的按鈕的ID,但不使用它,所以我改變了它。此外,我添加了一個return false以防止按下回車鍵的默認行爲(儘管此部分在Opera中不起作用:您需要在該瀏覽器中取消keypress事件):

function doClick(buttonId, e) 
    { 
    if (e.keyCode == 13) 
     { 
     // Get the button the user wants to have clicked 
     var btn = document.getElementById(buttonId); 
     if (btn) 
     { 
      btn.click(); 
      return false; 
     } 
    } 

}

0

的onkeydown

if (event.keyCode == 13) { 
    document.getElementById('submit').click(); 
    return false; 
}