捕获回车键以使用JavaScript点击按钮 [英] Capturing the Enter key to cause a button click with javascript
本文介绍了捕获回车键以使用JavaScript点击按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想捕捉回车键来点击按钮
i want to Capturing the Enter key to cause a button click
我有这个javascript:
i have this 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
}
}
}
with html
<input type="button" id="submit" value="Search" onClick="doSomeThing();" />
<input type="text" name="search" onKeyPress="doClick('submit',event)" />
这对于IE浏览器来说可以正常工作,但它并不适用于Firefox,
this is work fine with IE browser but it didn't with Firefox,
为什么?任何人都可以修复这个JavaScript代码在所有浏览器上工作。
Why ? can anybody fix this javascript code to work on all browsers.
谢谢
推荐答案
您应该不使用内联事件处理函数:
You should really not use inline event handlers:
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应该看起来像这:
Your HTML should then look like this:
<input type="button" id="submit" value="Search"/>
<input type="text" name="search" id="search" />
这篇关于捕获回车键以使用JavaScript点击按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文