2017-05-10 52 views
-1

我從數據listCards中讀取並使用jQuery顯示循環中的卡片列表。使用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>

所以我到目前爲止已經做的是

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

 
\t \t \t \t \t function staticListCards(){ 
 
\t \t \t \t \t \t console.log("Called"); 
 
\t \t \t \t \t \t $.each(listCards, function (index, value) { 
 
\t \t \t \t \t \t \t console.log(value); 
 
\t \t \t \t \t \t \t }); \t \t 
 
\t \t \t \t \t }

+2

你設置'listCards = staticListCards',然後調用'listCards.forEach(...'。因此,你打電話'的forEach()'上'function', –

+0

刪除此'var listCards = staticListCards; console.log(listCards);'並檢查 –

回答

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>

+0

@Arun Kumar:試試這個 –

+0

我無法讀取listCards的值,因爲它是loa在頁面級別和JS文件中的腳本標記內我正在寫代碼staticListcard() –

+0

你可以讓自己清楚嗎?我沒有得到你 –

-1

您應該使用Jquery的每個循環,如:

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

在此代碼「價值」意味着「listCards」單一元素,因此您可以使用它,你directy不需要使用索引 我希望它會幫助你

+0

我已經做了更改,但我越來越多隻有一個空的控制檯陣列 –

+0

您的「listCards」可能爲空,請檢查它的大小 –