简体   繁体   English

Javascript动态创建元素和onclick函数

[英]Javascript dynamically create elements and onclick functions

I need to do the following things: 我需要做以下事情:

  • First, fetch data paths on a server. 首先,获取服务器上的数据paths The data contains an array of path and the length is unknown. 数据包含path数组,长度未知。

  • Then I create a list-group where each list-group-item stands for a path . 然后,我创建一个list-group ,其中每个list-group-item代表一个path

  • Finally, I set the click function of each of the list-group-item which displays the correponding path in the data array. 最后,我设置每个list-group-itemclick函数,该函数在数据数组中显示相应的path

Here's the code 这是代码

var i = 0;
for(path of paths) {
  i++;
  $("#list_path").append('<a id="list-path-' + i + '" class="list-group-item tooltip-button"">' + "Path " + i + '</a>');
  $("#list-path-" + i).click(function() { console.log(path) })
}

However, no matter which list-group-item I click, only the last path element is shown. 但是,无论我单击哪个list-group-item ,都仅显示最后一个path元素。 I guess the problem is that only a pointer of path is assigned to the click function, which in the end of the for loop, always points to the last path . 我猜问题是,仅将path的指针分配给click函数,该函数在for循环的末尾始终指向最后一个path

How can I set the click function to display different path ? 如何设置点击功能以显示不同的path

Thanks. 谢谢。

You can use closure 您可以使用闭包

var i = 0;
for(path of paths) {
  i++;
  $("#list_path").append('<a id="list-path-' + i + '" class="list-group-item tooltip-button"">' + "Path " + i + '</a>');
  $("#list-path-" + i).click((function(path) {
      // return function wich has own variable path
      return function () { console.log(path) };
  })(path))
}

You have to do this 你必须这样做

$("#list-path-" + i).click(function() { console.log($(this).text()); })

Because of closure, path is the last value of the for loop. 由于关闭,路径是for循环的最后一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM