0

I am trying to write jason data into separate divs with class .name and data-key za data attr. I have problem with data and getting the right index for that.

Here is my buggy attempt. Console.log writes all keys, but the last function doesn't give divs the data attr

$.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");
              container.appendChild(div);
           });


        $.each((".name"), function(index) {
          $(this).data("key", keys[index]);
          console.log(keys[index]);
        });
4

2 回答 2

1

please try with this updated code

$.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");
          container.appendChild(div);
       });


    $(".name").each(function(index) {
      $(this).data("key", keys[index]);
      console.log(keys[index]);
    });
于 2013-10-22T06:17:27.590 回答
0

You missed a $ in ('.names') $.each try this,

$.each($(".name"), function(index) {
// ----^ use $ here
    $(this).data("key", keys[index]);
    console.log(keys[index]);
});

or simply,

$(".name").each(function(index) {
    $(this).data("key", keys[index]);
    console.log(keys[index]);
});

You can add key while adding element in container like,

var i=0;
var container = document.querySelector(".link-names");
names.forEach(function(name) {
      var div = document.createElement('div');
      div.innerHTML = name;
      $(div).addClass("name");
      $(div).data("key", keys[i]);// set data here
      container.appendChild(div);  
      i++;            
});
于 2013-10-22T06:12:55.203 回答