使用Jquery读取和显示数据

时间:2017-05-10 07:23:55

标签: javascript jquery

我从数据listCards读取并使用jquery在循环中显示卡片列表。

但我在控制台中只得到一个空数组。

请告诉我我做错了什么?



<script>
var listCards = [{
    "cardTitle": "Sample Ttile",
    "cardDate": "05 April 2017",
    "cardLinkURL": "#",
    "cardLinkDTM": "data-tracker-id=\"cards_1_1\" data-tracker-type=\"button\" data-tracker_ei=\"cards_1_1\" "
},
{
    "cardTitle": "Sample Ttile 2",
    "cardDate": "05 April 2017",
    "cardLinkURL": "#",
    "cardLinkDTM": "data-tracker-id=\"cards_1_1\" data-tracker-type=\"button\" data-tracker_ei=\"cards_1_1\" "
}]
</script>
&#13;
&#13;
&#13;

所以我到目前为止所做的是

&#13;
&#13;
$(".list-view").on('click', staticListCards);

					function staticListCards(){
						console.log("Called");
						$.each(listCards, function (index, value) {
							console.log(value);
							});		
					}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

尝试$.each()

它是一个通用的迭代器函数,可用于无缝迭代对象和数组。

var listCards = [{
    "cardTitle": "Sample Ttile",
    "cardDate": "05 April 2017",
    "cardLinkURL": "#",
    "cardLinkDTM": "data-tracker-id=\"cards_1_1\" data-tracker-type=\"button\" data-tracker_ei=\"cards_1_1\" "
  },
  {
    "cardTitle": "Sample Ttile 2",
    "cardDate": "05 April 2017",
    "cardLinkURL": "#",
    "cardLinkDTM": "data-tracker-id=\"cards_1_1\" data-tracker-type=\"button\" data-tracker_ei=\"cards_1_1\" "
  }
];
var len = listCards.length;
var txt = "";
$.each(listCards, function(key, value) {
console.log(value);
  txt += "<tr><td>" + value.cardTitle + "</td><td>" + value.cardDate + "</td></tr>";
});
if (txt != "") {
  $("#table").append(txt);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table">
  <tr>
    <th>Title</th>
    <th>Date</th>
  </tr>
</table>

答案 1 :(得分:-1)

你应该像每个循环一样使用Jquery:

$.each(listCards, function(index, value) {
    }

在此代码中“value”表示“listCards”的单个元素,因此您可以直接使用它,不需要使用索引 我希望它会对你有所帮助