简体   繁体   中英

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). Something like this:

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

Each object have some info that I use to populate an html template. 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. 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). 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...

You should not set your htmls variable in the loop. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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