使用键盘按键触发jQuery的点击事件

3
我在我的网站上有一个“上一页”和“下一页”的链接,我希望能使用左右箭头来触发它们。
实际上,我可以通过箭头键触发链接吗?
谢谢!
3个回答

5
$(document).keydown(function(e){
    e.preventDefault();    //this may not be necessary

    if (e.keyCode == 37) { 
       $('#previous').click();
    }
    else if (e.keyCode == 39) { 
       $('#next').click();
    }
});

字符代码:

37 - 左

38 - 上

39 - 右

40 - 下


5

这是有效的:

var a1 = $('#a1')[0],
    a2 = $('#a2')[0];

$(window).keydown(function (e) {
    if ( e.which === 37 ) {
        window.location.href = a1.href;        
    } else if ( e.which === 39 ) {
        window.location.href = a2.href; 
    }
});

实时演示: http://jsfiddle.net/simevidas/SxeeT/2/


4
您可以像这样调用单击事件:
$(document).keydown(function(e) {
    e.stopPropagation(); // not sure if you will need this but it should stop horizontal scrolling
    if(e.keyCode === 37) {
        $("#previous").click();
    } else if(e.keyCode === 39) {
        $("#next").click();
    }
});

Here is a jsfiddle in action.


谢谢你的回复!代码可行但无法触发href链接。我真正需要的是“点击”链接,网站实际上会跳转到a标签中的href。这可能吗? - Mark
尝试一下 - 我将div更改为锚点。 - John Kalberer
$("#previous").click(); 只会触发点击处理程序,但是 $("#previous")[0].click(); 将模拟点击并处理锚标签 href 值和点击处理程序(后者是原生 DOM 的 click,而前者是 jQuery 方法)。 - Tim Tisdall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接