javascript将对象值写入div

时间:2016-08-02 19:40:58

标签: javascript jquery html

我需要使用循环或某些函数(如果存在)将track对象的值写入plTitle。请帮助我不要在没有JavaScript的情况下这样做,但我不是很擅长,所以我需要你的帮助。



tracks = [{
  "track": 20,
  "name": "Magus - Smith St. Basement (01/08/04)",
  "length": "05:46",
  "file": "SSB01_08_04_M"
}, {
  "track": 21,
  "name": "Beneath The Painted Eye - Smith St. Basement (06/06/03)",
  "length": "13:08",
  "file": "SSB06_06_03_BTPE"
}];

$('.plItem .plTitle').each(function() {
  var trackName;

  for (var key in tracks) {
    trackName = ''
    var obj = tracks[key];
    naslov = obj.name;
    $(this).replaceWith('<div class="plTitle">' + trackName + '</div>');
  }
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="plwrap">
  <div class="plItem">
    <div class="plTitle"></div>
  </div>
  <div class="plItem">
    <div class="plTitle"></div>
  </div>
</div>
&#13;
&#13;
&#13;

如果您需要其他信息,请告诉我们!

3 个答案:

答案 0 :(得分:2)

您可能不需要.each - 这里的功能。 您可以在.text()使用函数作为参数:

$('.plItem .plTitle').text(function( index ) {
  return tracks[index].name;
});

这将从你的tracks数组中的元素索引的相应元素中写出movei的标题。

Example

答案 1 :(得分:1)

tracks = [{
  "track": 20,
  "name": "Magus - Smith St. Basement (01/08/04)",
  "length": "05:46",
  "file": "SSB01_08_04_M"
}, {
  "track": 21,
  "name": "Beneath The Painted Eye - Smith St. Basement (06/06/03)",
  "length": "13:08",
  "file": "SSB06_06_03_BTPE"
}];

var plwrap = document.querySelector(".plwrap");
var tmplItem = document.getElementById("tmplItem").content;

while (plwrap.firstChild) {
  plwrap.removeChild(plwrap.firstChild);
}

tracks.forEach(function (track, indice) {
  var newItem = document.importNode(tmplItem, true);
  var plTitle = newItem.querySelector(".plTitle");
  plTitle.textContent = track.name;
  plwrap.appendChild(plTitle);
});
<template id="tmplItem">
  <div class="plItem">
    <div class="plTitle"></div>
  </div>
</template>
<div class="plwrap">

</div>

答案 2 :(得分:0)

你很接近,但是你的变量名称搞得一团糟。这是循环部分的一种可能解决方案:

for (var key in tracks) {
    var obj = tracks[key];
    trackName = obj.name;
    $(this).replaceWith('<div class="plTitle">' + trackName + '</div>');
}

不同之处在于naslov变量将名称更改为trackName