0

I am trying to create an easy way for my users to select the trigger key that makes the code work altogether. I have this so far.

var triggers = {space:"32",enter:"13",tab:"9"};
var triggerKeys = ["space","enter"];

$('input').on('keypress',function(event) {
 var unicode= event.keyCode ? event.keyCode : event.which;
   if(unicode === triggers[triggerKeys]) {
       //code initiation here
   }

Though of course this doesn't work. Any ideas on how I could possibly make it so in the array of triggerKeys the code is initiated, as well if they have more than one triggerKeys?

Code works for just one Trigger. Should I for loop the triggerKeys for more than one?

4

2 回答 2

1

不知道你在追求什么,但我会做这样的事情:

$('input').on('keypress',function(e) {
    switch (e.which) {
        case 32: //space
            console.log('space');
            break;
        case 13: //enter
            console.log('enter');
            break;
        case 9: //tab
            console.log('tab');
    }
});

因为使用一个数组作为另一个数组的键似乎对我不起作用?

如果您只是想检查一个键是否存在于数组中,请存储键码:

var triggerKeys = [32, 13, 9];

$('input').on('keypress',function(e) {
    if ( $.inArray(e.which, triggerKeys) != -1 ) {
       // one of the triggerkeys was pressed
    }
});

编辑:

这是您正在使用的地图的另一个示例,并检查是否按下了触发键:

var triggerKeys = ["space","enter", "tab"];
var triggers    = {space: 32, enter: 13, tab: 9};

$('input').on('keypress',function(e) {
    var arr = $.map(triggerKeys, function(el, i) {return triggers[el];});
    if ( $.inArray( e.which, arr ) != -1 ) {
        console.log('trigger key pressed')
    }
});

小提琴

于 2013-06-09T20:20:29.167 回答
0

如果您希望根据变量的值运行一些代码,unicode那么只需检查集合中是否存在值就足够了。

一种简单的方法是为您的集合使用数组

var triggerKeys = [32, 13];

然后检查如下:

if (triggerKeys.indexOf(unicode) >= 0) {
    // ...
}

但根据MDN 文档 indexOf,可能并不适用于所有浏览器。

或者,您可以使用以下命令模拟一组:

var triggerKeys = {32: true, 13: true};

然后说

if (unicode in triggerKeys) {
    // ...
}

编辑

为了提高代码的可读性,您可以继续使用定义键名和键码的方法:

var triggers = {space: 32, enter: 13, tab: 9};
var triggerKeys = ["space", "enter"];

然后将根据触发器计算实际的触发键代码

var triggers = {space:"32",enter:"13",tab:"9"};
var triggerKeys = ["space", "enter"];
var triggerKeyCodes = {};

for (var i = 0; i < triggerKeys.length; i += 1) {
    triggerKeyCodes[triggers[triggerKeys[i]]] = true;
}

这使triggerKeyCodes对象看起来像{32:true, 13:true}。然后你可以写:

if (unicode in triggerKeyCodes) {
    // ...
}

现场演示:http: //jsbin.com/eqoyag/5/edit

由于您已经在使用 jQuery,因此 adeneo 的答案更好。即将发布的 JavaScript 版本将具有一些不错的功能(理解、映射等),这将使原始 JavaScript 版本更清晰。

于 2013-06-09T20:24:45.060 回答