当按键按下时,如何使用javascript加载新页面

How can I use javascript to load a new page when a key is pressed down?

本文关键字:何使用 javascript 新页面 加载      更新时间:2023-09-26

我有:

<a id="nextPage" href="somepage.php?name=foo">Next Page</a>

当有人按下键盘上的箭头按钮时,我想将用户重定向到锚标记中包含的href。如何使用javascript/jquery实现这一点?

我在想这样的事情:

window.location = $('#nextPage').attr('href');

有什么想法吗?

$(document).on('keydown', function (event) {alert(event.type);
    if (event.which == 37) {
        $('#prevPage').trigger('click');
        //or
        window.location = $('#prevPage').attr('href');
    } else if (event.which == 39) {
        $('#nextPage').trigger('click');
        //or
        window.location = $('#nextPage').attr('href');
    }
});​

下面是一个演示:http://jsfiddle.net/jasper/VprbW/2/

您还可以访问其中一个链接的href属性以更快地执行:

window.location = document.getElementById('nextPage').href;

您想要使用onkeypress事件。

http://www.javascriptkit.com/jsref/eventkeyboardmouse.shtml

描述如何使用此事件,并为所需的任何按钮提供密钥代码生成器。