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