簡體   English   中英

javaScript將事件綁定到按鈕數組

[英]javaScript bind event to array of buttons

新手問題,我嘗試創建按鈕數組,綁定單擊事件並將變量“編輯器”推送到回調函數;

  buttons = {
    save:{
      name:  "save",
      title: "save",
      action: function(editor) { alert('Save cliked.'); console.log(editor);}
    },
    preview:{
      name:  "preview",
      title: "preview",
      action: function(editor) { alert("Preview clicked."); console.log(editor);}
    },
    format:{
      name:  "format",
      title: "format",
      action: function(editor) { alert('Format clicked.'); console.log(editor);}
    }
  };


  for (var key in buttons) {
    butHash = buttons[key];
    var button = panel.appendChild(document.createElement("a"));
    button.setAttribute("title", butHash.title);
    button.setAttribute("class", "cm-panel-button " + butHash.name);
    button.textContent = "";
    console.log(button);
    editor = "some editor instance"
    $(button).on('click', function(){
      console.log(butHash.name);
      butHash.action(editor);
    });
  };

當我單擊任何一個此按鈕時,我總是看到上一次回調“單擊格式”。 我做錯了什么?

Javascript閉包:)您的代碼很好,您只需要將for循環的內部移到一個單獨的函數中以創建新的作用域,因為在Javascript中,閉包是在函數級別而非塊級別創建的。

for(var key in buttons){
  createButton(key);
}

function createButton(key){
  var butHash = buttons[key]
  ...
}

...應該這樣做。

如果您想了解有關閉包的更多信息,我建議例如這個問題,或者可能是這個 問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM