![](/img/trans.png)
[英]How can I loop through an array of objects using a 'for loop' and print the results in a template literal
[英]How to loop through array inside template literal
我正在嘗試在模態框內的一些模板文字代碼中運行一個循環。
因此,Ajax 請求的結果...我縮短了所有代碼以減少行數。
.done(function (data) {
var itemsList = $.each(data, function (index, item) {
'<p>' + item.prod_name + '<p>';
});
再次,縮短模態代碼。
var modal = `<div class="modal-body">`
+ itemsList +
`</div>`;
輸出的只是 [object object] 但如果我 console.log 我的數據,那么我會取回正確的數據。
您需要將數組轉換為字符串:
data=[{prod_name:1},{prod_name:2}]; var itemsList = $.map(data, function (item, index) { return '<p>' + item.prod_name + '<p>'; }).join(''); console.log(itemsList);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
請使用var modal = "<div class="modal-body">" +JSON.stringify(itemList) +"</div>";
JSON.stringify(itemList)
將為您提供 object 中的數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.