我在ERB页面上有几个link_to标签,它们被设置为带有Bootstrap(btn类)的按钮。如何将Enter键绑定到其中一个?
答案 0 :(得分:1)
我假设当你说“将Enter键绑定到其中一个”时,你的意思是“当用户按Enter键时,它们会按照我选择的链接。”
要完成此操作,我会在您要关注的链接标记上添加一个ID。对于下面的示例,我将使用#follow-me
然后,你需要使用Javascript。假设你正在使用jQuery,就像这样:
var ENTER = 13; //This is the js keycode for ENTER
function my_custom_keypress(e){
key = e.which;
if(key == ENTER){
var my_target_url = $('a#follow-me').attr('href'); //Figures out where your link goes...
window.location = my_target_url(); //...and sends the user to that URL.
}
}
$(document).on('keydown', my_custom_keypress); //when user presses a key, triggers our fxn
如果你真的想在目标链接上触发点击事件而不是强行链接用户,你可以稍微修改一下代码(再次,这需要jQuery):
var ENTER = 13; //This is the js keycode for ENTER
function my_custom_keypress(e){
key = e.which;
if(key == ENTER){
$('a#follow-me').trigger('click');
}
}
$(document).on('keydown', my_custom_keypress); //when user presses a key, triggers our fxn
应该这样做,祝你好运!