1

我正在从我们的后端取回包含键盘快捷键信息的数据。这是我将收到的内容的简化版本:

    { code: "r", message: "test R" },
    { code: "s", message: "test S" },
    { code: "c", message: "test C"}

“代码”指定哪个键将激活键盘快捷键,消息将粘贴在输入框中。

我正在使用Mousetrap库,它允许我编写如下函数:

Mousetrap.bind('shift+^+r', function () {
    alert("test");
});

我的问题是:有没有办法在运行时根据带回的数据编写这些函数?因此,对于 JSON 对象中的每个项目,都需要一个函数来处理快捷方式。

我试过这个:

    var html = document.getElementById("shortcuts").innerHTML;
    document.getElementById("shortcuts").innerHTML = html + "<script> Mousetrap.bind('shift+^+r', function () { alert('test) })); <\/script>"

我不知道这是否是一种好的做法,因为我对 JS 还是很陌生,但这是我唯一能想到的。但它不起作用。

4

2 回答 2

3

当然。听起来很容易。只需创建一个接受对象的单独函数,同时获取codemessage属性并Mousetrap.bind(str, func)在运行时调用

function bindKey(input){
    const code = input.code;
    const message = input.message;

    const bindStr = "shift+^+" + code; //idk if you need shift here but modify as needed

    Mousetrap.bind(bindStr, function(){
          alert(message);
    });
}

通过使用

bindKey({code: "r", message: "test R"});
bindKey({code: "c", message: "test C"});
bindKey({code: "d", message: "test D"});

如果你有一个对象数组,只需遍历它们并调用bindKey()

myArray.forEach(bindKey);
// or
for (const i of myArray) bindKey(i);

无需编写脚本元素。只需编写函数并在运行时调用它。为什么需要渲染脚本标签超出了我的范围。


下面测试

function bindKey(input){
   const code = input.code;
   const message = input.message;

   const bindStr = "shift+^+" + code; //idk if you need shift here but modify as needed
    
    Mousetrap.bind(bindStr, function(){
          console.log(message);
    });
}
    
bindKey({code: "r", message: "test R"});
bindKey({code: "c", message: "test C"});
bindKey({code: "d", message: "test D"});
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js"></script>

于 2019-07-18T10:39:44.547 回答
2

您可以遍历所有对象,将键与code每个对象绑定后,您可以搜索数组并选择要显示消息的元素。适度的实施:

var data = [{code:"r",message:"test R"},{code:"s",message:"test S"},{code:"c",message:"test C"}];

//use forEach to go through each item in data
data.forEach(key => {
  //call MouseTrap bind on key.code, key is one of the element in data
  Mousetrap.bind('shift+^+' + key.code, (e) => {
    //e is the event variable from the keystroke
    
    //data.find will find the element which has the key value(e.key) from the event
    //converting into lowercase because data is in lowercase too
    var element = data.find(d => {
      //check if code of the element matches e.key
      if (d.code == e.key.toLowerCase()) return d;
    });
    //log element.message
    console.log(element.message);
  });
});
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js"></script>


来自@Bergi@AZ_的建议:

var data = [{code:"r",message:"test R"},{code:"s",message:"test S"},{code:"c",message:"test C"}];

data.forEach(({code, message}) => Mousetrap.bind(`shift+^+${code}`, () => console.log(message)));
<script src="https://craig.global.ssl.fastly.net/js/mousetrap/mousetrap.min.js"></script>

于 2019-07-18T10:45:03.287 回答