出于本次测试的目的,我有一些基本的 html:
<a href="https://www.google.co.uk" class="prev">Previous</a>
<a href="https://jsfiddle.net" class="next">Next</a>
我有一个相当简单的 jquery 函数:
var prev = $('.prev');
var next = $('.next');
$('body').on('keydown',function(e){
if(e.which == 37){
prev.trigger('click');
}else if(e.which == 39){
next.trigger('click');
}
console.log(e.which);
e.preventDefault();
});
控制台正在记录按下的每个键,但这并没有将单击事件绑定(bind)到每个 href,我不确定为什么。
此外,我认为使用 e.preventDefault();
会阻止页面上的其他关键操作。在我的应用程序的其他 keyCode 函数中,我没有使用 return false
或 preventDefault();
是否可以将 anchor 包装在 div 中并将 keydown 仅绑定(bind)到该容器,例如:
<div class="nav">
<a href="https://www.google.co.uk" class="prev">Previous</a>
<a href="https://jsfiddle.net" class="next">Next</a>
</div>
$('.nav').on('keydown', function(){} // etc
我这里有一个jsfiddle:https://jsfiddle.net/lharby/sva0a4d1/
最佳答案
你可以试试这个:
$('body').on('keydown',function(e){
if(e.which == 37){
$('a.prev')[0].click()
}else if(e.which == 39){
$('a.next')[0].click()
}
});
关于javascript - 使用 jQuery 将箭头键绑定(bind)到导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39193162/