2013-02-06 52 views
0

我試圖創建一個Web應用程序,將允許用戶定義自定義JavaScript函數,然後添加一個按鈕,他們的用戶界面,以及預製件的功能。jQuery的綁定自定義函數附加元素

下面是代碼

var customCommands = { 
    command1: { 
    text: 'Hello Console', 
    cFunctionRun: function() { 
     console.log('hello Console!'); 
    } 
    }, 
    command2: { 
    text: 'Hello World', 
    cFunctionRun: function() { 
     alert('hello World!'); 
    } 
    } 
} 

然後我寫了一個小功能循環,雖然並建立按鈕,並將它們添加到用戶界面的一個樣本。問題是,當我的元素追加到比點擊按鈕沒有工作時用戶界面...

這裏是我試過

for (var cmd in customCommands) { 
    command = customCommands[cmd]; 
    button = $('<button/>').html(command.text).on('click', 
     function(){ 
     console.log(command.text); 
     command.cFunctionRun(); 
     } 
    ); 
} 
buttonContainer.append(button); 

的方法之一現在我的循環建立的一切只是罰款,甚至.on('click')的作品,但它總是顯示的歷史添加命令的文本?

這裏是http://jsfiddle.net/nbnEg/顯示發生了什麼。

+0

你能加入更多內容?什麼你已經展示作品http://jsfiddle.net/nbnEg/ – bfavaretto

+0

第二代碼在看...生病立即更新,包括循環 –

回答

2

當你真正點擊,命令變量指向最後一個命令(如整個循環已經開)。你應該維護每個按鈕的數據狀態,告訴它調用哪個命令。你應該做這個。

for(var i in customCommands) { 
    if(customCommands.hasOwnProperty(i)){ //this is a pretty important check 
    var command = customCommands[i]; 
    button = $('<button/>').html(command.text).data("command_name", command).on('click', function(){ 
     console.log($(this).data("command_name").text); 
     $(this).data("command_name").cFunctionRun(); 
    }); 

    $("body").append(button); 
    } 
} 

JSFiddle

+0

看起來很漂亮! –

+0

將其標記爲答案然後:) –

+0

需要等待10分鐘... –

1

所有你需要的是通過與功能的參數,你應該嘗試this

+1

好這項工作如果函數是很多更復雜的則只是顯示文本。用戶將使用它來幫助自動計算並運行自定義報告? –

0

這是一個(丟失)關閉的問題。事件處理程序將在循環的最後一次迭代中保留對命令值的引用。爲了解決這個問題,你可以創建一個新的範圍,使用立即調用函數:

for(var cmd in customCommands) { 
    (function(command){ 
     button = $('<button/>').html(command.text).on('click', 
      function(){ 
      console.log(command.text); 
      command.cFunctionRun(); 
      } 
     ); 
     buttonContainer.append(button); 
    }(customCommands[cmd])); 
} 
0

由於button S的關係是獨一無二的(沒有理由爲創建重複),我設置按鈕idname customCommands(本例中爲command1和command2)。這個例子很容易適用於使用任何相關屬性(data- *,name等等)。

document上創建一個click事件偵聽器,只要您的button s之一被按下。然後調用與給定的id相關的函數。

$(document).on("click", "button", function(){ 
    customCommands[this.id].cFunctionRun(); 
}); 

for(var command in customCommands){ 
    var button = $('<button id="' + command +'"/>').html(customCommands[command].text); 
    $("body").append(button); 
} 

EXAMPLE

+0

謝謝,我想到了這一點,但我不喜歡使用ID標籤的想法。謝謝你。 –

+0

@ RobertE.McIntosh - 任何屬性都可以正常工作,但是這裏最大的區別在於,事件通過附加事件到'document'來實現'delegate'事件。如果您將動態內容添加到頁面,則這是您應該去的方式。 – Chase

相關問題