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

时间:2013-02-06 20:27:07

标签: javascript jquery

我正在尝试创建一个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/来说明会发生什么。

4 个答案:

答案 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

答案 1 :(得分:1)

您只需要通过函数传递参数,您应该尝试this

答案 2 :(得分:0)

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

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]));
}

答案 3 :(得分:0)

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

click上创建一个document事件监听器,只要您按下button一个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); } 关联的函数。

{{1}}

<强> EXAMPLE

相关问题