我正在尝试创建一个 Web 应用程序,允许用户定义自定义 JavaScript 函数,然后向其用户界面添加一个按钮来很好地执行该函数。
这是代码示例
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/显示发生了什么。
最佳答案
当您实际单击时,命令变量指向最后一个命令(因为整个循环已经运行)。您应该维护每个按钮的数据状态,告诉它要调用哪个命令。你应该这样做。
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);
}
}
关于javascript - jQuery 将自定义函数绑定(bind)到附加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14738154/