jQuery将自定义函数绑定到附加元素 [英] jQuery bind custom function to appended element

查看:59
本文介绍了jQuery将自定义函数绑定到附加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个Web应用程序,该应用程序将允许用户定义自定义JavaScript函数,然后在其用户界面中添加一个按钮,以很好地执行该功能.

I am trying to create a web app that will allow a user to define a custom JavaScript function and then add a button to their user interface that well preform that function.

这是代码示例

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

然后,我编写了一个小函数,该函数循环并构建按钮并将其添加到用户界面.问题是,当我将元素附加到用户界面上,而不是单击按钮时,什么都不起作用...

Then I wrote a small function that loops though and builds the buttons and adds them to the user interface. The problem is when I append the elements to the user interface than click on the buttons nothing works...

这是我尝试过的方法之一

Here is one of the methods I tried

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')也可以正常工作,但是它始终显示最后添加的命令的文本吗?

Now my loop builds everything just fine and even the .on('click') works, but it always displays the text of the lasted added command?

这是 http://jsfiddle.net/nbnEg/,以显示发生了什么.

here is http://jsfiddle.net/nbnEg/ to show what happens.

推荐答案

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

When you actually click, the command variable points to last command (as the whole loop has already run). You should maintain data state per button which tells it which command to invoke. You should do this.

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

这篇关于jQuery将自定义函数绑定到附加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆