简体   繁体   English

在动态创建的html上设置数据信息

[英]Setting data info on dynamically created html

I have a JSON response from a server, which returns me a array with 32 objects (in this case). 我有一个来自服务器的JSON响应,它返回一个包含32个对象的数组(在这种情况下)。 Something like this: 像这样:

[{object1},{ object2},{ object3}, etc]. 

Each object have some info that I use to populate an html template. 每个对象都有一些我用来填充html模板的信息。 For that, I just use a simple loop: 为此,我只使用一个简单的循环:

     for(var i = 0; i < api_empresaListar.length; i++)
          {
            var item = api_empresaListar[i];
            var htmls;
            htmls = $('...lots of html code');
...

Then it's just a simple matter of finding/changing the values, and append items on the DOM. 然后,只需查找/更改值,然后将项目附加到DOM上,就很简单了。 Everything works fine. 一切正常。 BUT, for some next parts of the code, I would like to access all the info from the object I used to build the html elements (I just show part of the info). 但是,对于代码的下一部分,我想从用于构建html元素的对象中访问所有信息(我只显示了部分信息)。 So, after searching a lot, I tried to use data, like this: 因此,经过大量搜索后,我尝试使用数据,如下所示:

var tp = htmls.find(".rl_grupo"); // the main div of each html element created in the loop
$(tp).data('key', api_empresaListar[i]); // here, I expected to just insert the object data in each created item.

But when I try it in the console, I got the object info as expected, but always from the last element in the array. 但是,当我在控制台中尝试时,我按预期方式获得了对象信息,但是总是从数组中的最后一个元素得到的。 Why is that happening? 为什么会这样呢? I believe it might be something stupid, but I can't figure it out. 我认为这可能有些愚蠢,但我无法弄清楚。

So, any ideas on how to solve this, or another method to make this work is appreciated. 因此,对如何解决此问题的任何想法,或完成此工作的另一种方法表示赞赏。 I made it work by setting some "display:none" placeholder html tags and populate those with the info I need later, but looks like a poor solution... 我通过设置一些“ display:none”占位符html标记使其工作,稍后用我需要的信息填充这些标记,但看起来是一个糟糕的解决方案...

You should not set your htmls variable in the loop. 您不应在循环中设置htmls变量。 I think that you crush its content every turn, that's why you only have the last item. 我认为您动不动就粉碎它的内容,这就是为什么只有最后一项的原因。 You should do something like this: 您应该执行以下操作:

var htmls = $('<div></div>');
for(var i = 0; i < api_empresaListar.length; i++) {
    htmls.append($('...lots of html code'));
}

How about setting an index number on each element inside of your html creating code, then iterating over the $('.rl_grupo') elements, like this? 怎么样在html创建代码的每个元素上设置索引号,然后像这样迭代$('。rl_grupo')元素?

$('.rl_grupo').each(function(){
  var index = $(this).data('index');
  var currentData = api_empresaListar[index];
  $(this).data('key', currentData);
})

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

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