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

标签 javascript html

我想捕获 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
            }
        }
   }

用 html

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

这在 IE 浏览器上工作正常,但在 Firefox 上不行,

为什么?任何人都可以修复此 javascript 代码以在所有浏览器上工作。

谢谢

最佳答案

你真的不应该使用内联事件处理程序:

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" />

关于javascript - 捕获 Enter 键以导致使用 javascript 单击按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4357654/

相关文章:

javascript - 将一个数组插入另一个数组?

Javascript onDrop 属性未分配

PHP 将 Excel 文件从 ".xls"转换为 ".xlsx"

javascript - document.getElementById 隐藏文本对于菜单中的书签不可见

javascript - 复制字段元素和重复项的位置

javascript - 如何使用来自不同包的相同 React 上下文?

javascript - jQuery 的 show() 和 hide() 在 IE8 中不起作用(当使用 IE 调试器时,代码突然起作用)

javascript - 避免 jQuery 代码重复

html - Unicode 字符作为 CSS 中列表项的元素符号

javascript - IE7 不支持本地存储