捕获Enter键以使用javascript导致按钮单击

Swe*_*ell 4 html javascript

我想捕获Enter键以使按钮单击

我有这个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
            }
        }
   }
Run Code Online (Sandbox Code Playgroud)

用html

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

这在IE浏览器上运行良好,但它不适用于Firefox,

为什么?任何人都可以修复此JavaScript代码以适用于所有浏览器.

谢谢

Jac*_*kin 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(); 
     }
  }
}
Run Code Online (Sandbox Code Playgroud)

您的HTML应如下所示:

<input type="button" id="submit" value="Search"/>
<input type="text" name="search" id="search" />
Run Code Online (Sandbox Code Playgroud)

  • OP使用事件处理程序属性的事实与问题无关,并断言OP不应该这样做是教条主义.使用事件处理程序属性并且不引入任何功能问题是完全有效的. (2认同)

Tim*_*own 5

我建议使用该keydown事件代替这种特殊情况,因为它简化了密钥检测:您可以keyCode在所有浏览器中使用.此外,您传递了要单击的按钮的ID,但之后没有使用它,所以我改变了它.另外,我添加了一个return false以防止按Enter键的默认行为,(虽然这部分在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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

}