![](/img/trans.png)
[英]JavaScript - Generating combinations from dictionary keys and keeping key names dynamically
[英]Dynamically set Mousetrap.bind() key combinations from an object
我從后端獲取了有關鍵盤快捷鍵信息的數據。 這是我將收到的簡明版本:
{ 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>
您可以遍歷所有對象,將鍵與來自每個對象的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>
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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.