开发者

JavaScript event that reloads the page

In the example code below I have a button that when clicked reloads the page, but hitting enter does not do so, how would one amend it so that hitting enter would also refresh the page?

&l开发者_如何转开发t;h3>click to refresh page</h3>
<input type="button" value="Refresh" onClick="history.go(0)">


You could set a key handler on the page itself if you want to catch any ENTER keypress anywhere:

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);
}


You can do it like this:

<h3>click to refresh page</h3>
<form onSubmit="history.go(0); return false;">
<input type="submit" value="Search"></form>


You need to set the focus. In your onload function:

var button = document.getElementById("mybutton"); 
button.focus(); 

You could also add an on key press event:

http://help.dottoro.com/ljlwfxum.php

http://www.devguru.com/Technologies/ecmascript/quickref/evhan_onkeypress.html


You could do by setting an event on the document.

Try this:

//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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜