简体   繁体   中英

mapping Json data and adding data attr

I have a difficulty with mapping my my Json data. I would like to add data attr to each div with .name class. So as the result is like that:

<div class="name" data-key="sth"> sty</div>

Key can be got like that: ['streme'].key

here is my buggy JS:

function getExistingLinks() {
          $.post( "http://0.0.0.0:9292/api/links", function( data ) {
            var names = data.map(function (i) {
            return i['link'].name
            });
            var keys = data.map(function (i) {
            return i['link'].key
            });
            var container = document.querySelector(".link-names");
                names.forEach(function(name) {
                    var div = document.createElement('div');
                    div.innerHTML = name;
                    $('div').addClass("name");
                    // $('div').each( function(index) {
                           $('div')[index].data("key") = keys[index];
                       }
                    container.appendChild(div);
                });
       });  
      return false;   
    }
names.forEach(function(name,index) {
  var div = document.createElement('div');
  div.innerHTML = name;
  $(div).addClass("name");
  $(div).data("key") = keys[index];
});

You need to remove the quotes in the $() selector!

As per your comment, may be try doing like:

var i = 0;
names.forEach(function(name) {
    var div = document.createElement('div');
    div.innerHTML = name;
    $('div').addClass("name");
    $('div').data("key", keys[i]);
    container.appendChild(div);
    i++;
});

the preferred method is to only add to the DOM once, as adding to the DOM will cause a redraw on each.

psuedo code as not sure what name represents in your innerHTML:

var divs = []; for (var i, len = names.length; i < len; i++) { divs.push($(''+name+'').data("key", keys[i])); }

$container.append(divs);

http://codepen.io/jsdev/pen/2866265243563efd79cf05a5b12202b3

尝试这样的事情

 $('.name').data('key') //will give you sth

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