2012-09-21 31 views
0

我試圖用鍵盤快捷鍵的https://github.com/stepanvr/js-shortcuts jquery插件。但是我堅持這個問題。我在json數據結構中定義快捷鍵數據。然後,我循環瀏覽這些快捷方式,並在需要輸出按下的快捷方式時報告錯誤的快捷方式。無論我按下Ctrl + Shift + P組合的哪一個快捷方式都會報告。我相信這與JavaScript如何處理這個處理函數有關。在關閉時輸出正確的變量值時出現問題

 
var data = { 
    'name' : 'Eclipse (Java)', 
    'version' : '1.0', 
    'hotkeys' : { 
     'Navigation' : { 
      'Ctrl+Shift+R'  : 'Open/Search for resources, e.g. files', 
      'Ctrl+Shift+T'  : 'Open/Search for Types', 
      'Ctrl+E'   : 'Allows to select an editor', 
      'Ctrl+F8'   : 'Shortcut for switching perspectives', 
      'Alt+Left'   : 'Go to previous/ next editor position in history', 
      'Ctrl+PageUp'  : 'Switch to previous/next editor', 
      'F3'    : 'Go to the declaration of this variable', 
      'Ctrl+Shift+P'  : 'Go to the matching bracket' 
     } 
    } 
}; 

var verify = function(msg) { 
    var node = document.getElementById('debug'); 
    node.innerHTML += msg + ' '; 
}; 

$(document).ready(function() { 
    for (var x in data.hotkeys.Navigation) { 
     $.Shortcuts.add({ 
      type:'down', 
      mask:x, 
      handler:function() { 
       verify(x); 
      } 
     }); 
    } 
    $.Shortcuts.start(); 
}); 

回答

2

您的問題是,在設置x變量正在改變,因爲循環那張回調的範圍,你必須將它包裝在一個封閉像這樣:

for (var x in data.hotkeys.Navigation) { 
    (function(x){ 
     $.Shortcuts.add({ 
      type:'down', 
      mask:x, 
      handler:function() { 
       verify(x); 
      } 
     }); 
    })(x); 
    } 
+0

YEAHHH,做過招!!! – davidgale

相關問題