简体   繁体   English

是否存在Javascript或jQuery事件,该事件在跟随键盘上的焦点链接时触发?

[英]Is there a Javascript or jQuery event that triggers on following a focused link with the keyboard?

I'm using jQuery focus() and blur() to highlight image links during keyboard navigation (tabbing) but need to be able to run some code when a link is followed via 'Enter' on the keyboard. 我在键盘导航(制表)期间使用jQuery focus()blur()突出显示图像链接,但是当通过键盘上的“ Enter”键跟随链接时,需要能够运行一些代码。

Is there a built in event which does this or do I need do something like bind keypress and check for the 'Enter' key? 是否有内置事件可以执行此操作,或者我需要执行诸如bind keypress并检查“ Enter”键吗?

<a href="http://www.google.com" id="testlink">CatchMe</a>

$('#testlink').attr("rel", $('#testlink').attr("href"));
$('#testlink').attr("href","");
$('#testlink').keydown(function(event) {
    if (event.keyCode == '13') {
        alert("Don't you dare!");
    }
    if (event.keyCode == '71') {
        location.href=$('#testlink').attr("rel");
    }
});

This code removes the href (stores it in rel). 此代码删除href(将其存储在rel中)。 Now you can catch the keydowns. 现在您可以掌握按键状态。 You can respond to the enter key (13) however you like (alert in this case). 您可以按自己喜欢的方式响应输入键(13)(在这种情况下,请提示)。 Afterwards you can let the browser follow the link after all, if you want. 之后,您可以根据需要让浏览器毕竟跟随该链接。 In this example however, I only let the browser follow the link when the 'g' key (code 71) is pressed. 但是,在此示例中,仅当按下“ g”键(代码71)时,我才让浏览器跟随链接。

Note that this also works when the href value is like 'javascript:alert("blah")'. 请注意,当href值类似于'javascript:alert(“ blah”)'时,这也适用。

Edit: this is a lot easier however (inspired by the answer to this question): 编辑:这是一个容易得多。然而(由回答启发这个问题):

$('#testlink').click(function () {alert("hi"); return false; });

(return true if you do want the link to be followed after the alert) (如果您确实希望在警报后点击链接,则返回true)

Look at the following: 请看以下内容:

focusin 专注于

focusout 聚焦

Also, if you are entering the key handling scene, than please read quirksmode 另外,如果您要进入密钥处理场景,则请阅读quirksmode

Final link is very important because every browser is special in its own way, ie some events get ignored, some get fired off when you don't expect them to. 最终链接非常重要,因为每种浏览器都有其自己的特殊方式,即某些事件被忽略,某些事件在您不期望的情况下被触发。

To elaborate on the reply by Jochem. 详细阐述Jochem的答复。 You can use .trigger() to create your own events like this: 您可以使用.trigger()创建自己的事件,如下所示:

$('#testlink').keydown(function(event) {
    if (event.keyCode == '13') {
        // alert("Don't you dare!");
        $('#testlink').trigger('enterdown');
    }
});

and also: 并且:

$('#testlink').bind('enterdown', function(event) {
    alert('Enter was pressed.');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM