在下面的示例代码中,我有一个按钮,当点击时重新加载页面,但按Enter键不会这样做,如何修改它以便按Enter键也会刷新页面?
<h3>click to refresh page</h3>
<input type="button" value="Refresh" onClick="history.go(0)">
答案 0 :(得分:1)
如果你想在任何地方捕捉任何 ENTER键,你可以在页面上设置一个键处理程序:
function catchCR(e) {
if (!e) {
e = window.event; // for IE
}
var key = 0;
if (e.keyCode) { key = e.keyCode; } // IE
if (e.which) { key = e.which; } // FF
if (key == 13 /* enter key */) {
history.go(0);
}
}
if (document.addEventListener) {
document.addEventListener("keydown", catchCR, true);
} else if (document.attachEvent) {
document.attachEvent("onkeydown",catchCR);
}
答案 1 :(得分:0)
您需要设置焦点。在你的onload函数中:
var button = document.getElementById("mybutton");
button.focus();
您还可以添加按键事件:
http://help.dottoro.com/ljlwfxum.php
http://www.devguru.com/Technologies/ecmascript/quickref/evhan_onkeypress.html
答案 2 :(得分:0)
你可以这样做:
<h3>click to refresh page</h3>
<form onSubmit="history.go(0); return false;">
<input type="submit" value="Search"></form>
答案 3 :(得分:0)
您可以通过在文档上设置事件来完成。
试试这个:
//Traditional Way
document.onkeypress = function(event){
event = event || window.event;
key=event.keyCode;
if (key == "13") //Enter
{
history.go(0);
}
};
//OR
function keyHandler(event){
event = event || window.event;
key=event.keyCode;
if (key == "13") //Enter
{
history.go(0);
}
}
//Modern W3c Way
if (document.addEventListener) {
document.addEventListener("keydown", keyHandler, false);
}
//IE Way
else if (document.attachEvent) {
document.attachEvent("onkeydown",keyHandler);
}