jQuery 如何创建和触发动态热键(键码和 :not() 选择器?)
我正在开发一个网络应用程序,我希望用户能够动态定义和触发热键。我希望有人能帮助我?
我用相关的 HTML 创建了一个 JSFiddle HERE 。
这是我的 javascript:
// Assign Hotkey (this seems to be working)
$('input.hotkey').keydown( function(event) {
var hkey = event.keyCode;
if ( hkey == $('span#hk').text()){
alert('This key is already in use');
} else
$(this).parent().parent().prev().find('span#hk').text(hkey);
});
// Fire Hotkey (the problem might be here?)
$(document).not('input').keydown( function (event) {
var hkey = event.keyCode;
if (hkey == $('span#hk').text()){
$("span#hk:contains("+hkey+")").parent().click();
}
});
// Play Selected Track
$('#track').live('click', function () {
// Fake Function
var title = $('#title', this).text();
alert(title + ' is playing...');
});
注意:我已经使用“空格”和“左/右”箭头键作为全局热键 - 有没有办法保护/防止它们被分配?
有没有比 .not('input') 更好的选择器来防止在输入输入期间触发轨道?
感谢您的帮助!
I have a web app that I'm working on that I would like the user to be able to define and trigger hotkeys dynamically. I hope someone can help me out?
I've created a JSFiddle HERE with the pertinent HTML.
Here's my javascript:
// Assign Hotkey (this seems to be working)
$('input.hotkey').keydown( function(event) {
var hkey = event.keyCode;
if ( hkey == $('span#hk').text()){
alert('This key is already in use');
} else
$(this).parent().parent().prev().find('span#hk').text(hkey);
});
// Fire Hotkey (the problem might be here?)
$(document).not('input').keydown( function (event) {
var hkey = event.keyCode;
if (hkey == $('span#hk').text()){
$("span#hk:contains("+hkey+")").parent().click();
}
});
// Play Selected Track
$('#track').live('click', function () {
// Fake Function
var title = $('#title', this).text();
alert(title + ' is playing...');
});
Note: I have already used the 'space' and 'left/right' arrow keys as global hotkeys - is there a way to protect/prevent them from being assigned?
Is there a better selector to use than .not('input') to prevent firing the track during input typing?
Thanks for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
$(document).not('input')
未找到所有不是input
标记的元素。它找到所有不是输入元素(都是其中之一)的文档节点(其中有一个)。您所做的就是将处理程序附加到文档
。由于父元素会收到其子元素触发的事件的通知,因此所有keydown
事件都由该函数处理。您应该使用
event.target
代替:if
语句意味着如果事件源自input
元素,则处理程序不会执行任何操作。$(document).not('input')
does not find all elements that are notinput
tags. It finds all the document nodes (of which there is one) that are not input elements (which is all one of them). All you've done is attached the handler to thedocument
. Because parent elements are notified of events triggered on their descendants, allkeydown
events are handled by this function.You should make use of
event.target
instead:The
if
statement means the handler does not do anything if the event originated on aninput
element.