使用JavaScript捕获回车键以触发按钮点击事件

4
我想捕获回车键以触发按钮点击。
我有以下 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代码使其在所有浏览器上都能正常工作吗?谢谢。”

你能详细说明正在发生什么吗?这个方法是否被调用了? - cwallenpoole
这个链接肯定会对你有所帮助: https://dev59.com/-XVC5IYBdhLWcg3w4VX6 - user1587696
4个回答

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应该如下所示:

您的HTML应该像这样:

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

2
OP使用事件处理程序属性这一事实与问题无关,声称OP不应该这样做是教条主义的。使用事件处理程序属性是完全有效的,不会引入任何功能问题。 - Tim Down
没用!我为了测试目的编写了一个警告框函数。 document.getElementById('submit').onclick = getMsg(); 但是当我打开页面时,警告框立即出现, 而且在IE上按回车键时可以正常工作,但在Firefox上无法正常工作! - Swell
@Swell 你需要分配函数引用,而不是调用返回值:document.getElementById('submit').onclick = getMsg; - Jacob Relkin
是的,这在Firefox上运行良好,但在IE上不行。我已经编辑过以便在IE上能够运行,请问你可以编辑你的解决方案并加入以下代码吗? if(window.event) event.keyCode = 0 else ev.preventDefault(); 而不仅仅是 ev.preventDefault(); 我想将您的解决方案设置为正确的解决方案,但请您先进行编辑。 - Swell

5

针对这种情况,我建议使用keydown事件,因为它简化了按键检测:在所有浏览器中都可以使用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;
        }
    }

}


向下滚动而不是向上滚动?我一直觉得释放更具直观感。这只是你的偏好还是真的有性能提升?(某些浏览器在向下滚动方面是否更好/更快?) - cwallenpoole
@cwallenpoole:我选择使用 keydown 的原因是为了保持与问题中相同的用户体验:OP 正在使用 keypress,它会在 keydown 之后立即触发。此外,它也符合本地浏览器的行为,当用户按下 Enter 键时提交表单,这是在按下键而不是释放键时触发的。 - Tim Down
我忘记了.click()方法以及表单在按下回车键而不是松开回车键时提交。谢谢,这真的帮助我解决了过去一个小时的头痛问题。 - pqsk

2

为什么不使用像jQuery这样的包装器js框架呢?它可以为您处理所有跨浏览器问题。我随口想到的是,这可能会起作用(但您应该进行验证):

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

0

onKeydown

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接