2013-02-06 118 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

相关问题