[英]JavaScript event that reloads the page
在下面的示例代码中,我有一个按钮,当单击该按钮时会重新加载页面,但按Enter却不会这样做,如何修改它,使按Enter也会刷新页面?
<h3>click to refresh page</h3>
<input type="button" value="Refresh" onClick="history.go(0)">
如果要在任何地方捕获任何 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);
}
您需要设置焦点。 在您的onload函数中:
var button = document.getElementById("mybutton");
button.focus();
您还可以添加一个按键事件:
http://help.dottoro.com/ljlwfxum.php
http://www.devguru.com/Technologies/ecmascript/quickref/evhan_onkeypress.html
您可以这样做:
<h3>click to refresh page</h3>
<form onSubmit="history.go(0); return false;">
<input type="submit" value="Search"></form>
您可以通过在文档上设置一个事件来完成。
尝试这个:
//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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.