我正在从我们的后端取回数据,其中包含有关键盘快捷键的信息。这是我将收到的简化版本:
{ 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 还是很陌生,但这是我唯一能想到的。虽然它不起作用。
最佳答案
当然。听起来很容易。只需创建一个接受对象的单独函数,同时获取 code
和 message
属性并在运行时调用 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>
关于javascript - 从对象动态设置 Mousetrap.bind() 组合键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57092554/