jQuery将自定义函数绑定到附加元素

我正在尝试创建一个Web应用程序,允许用户定义自定义JavaScript函数,然后向用户界面添加一个按钮,以完成该function。

这是代码示例

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 = $('

现在我的循环构建一切都很好甚至.on('click')都能正常工作,但它总是会显示已添加命令的文本?

这里是http://jsfiddle.net/nbnEg/来显示会发生什么。

实际单击时,命令变量指向最后一个命令(因为整个循环已经运行)。 您应该维护每个按钮的数据状态,告诉它调用哪个命令。 你应该做这个。

 for(var i in customCommands) { if(customCommands.hasOwnProperty(i)){ //this is a pretty important check var command = customCommands[i]; 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

你只需要通过函数传递参数,你应该试试这个

这是一个(缺失)关闭问题。 事件处理程序将在循环的最后一次迭代中保留对command的值的引用。 要解决此问题,您可以使用立即调用的函数创建新范围:

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

由于button s应该是唯一的 (没有理由创建重复项),我将按钮id设置为customCommands的name (本例中为command1和command2)。 这个例子很容易适应使用任何相关属性(data- *,name等)。

无论何时按下某个button ,都会在document上创建一个click事件侦听器。 然后调用与给定id相关联的函数。

 $(document).on("click", "button", function(){ customCommands[this.id].cFunctionRun(); }); for(var command in customCommands){ var button = $('').html(customCommands[command].text); $("body").append(button); }