[英]How to loop through array inside template literal
I am trying to run a loop inside some template literal code, inside a modal.我正在尝试在模态框内的一些模板文字代码中运行一个循环。
So, the result of an Ajax request... I have shortened all the code to keep the line count down.因此,Ajax 请求的结果...我缩短了所有代码以减少行数。
.done(function (data) {
var itemsList = $.each(data, function (index, item) {
'<p>' + item.prod_name + '<p>';
});
Again, shortened modal code.再次,缩短模态代码。
var modal = `<div class="modal-body">`
+ itemsList +
`</div>`;
All that is outputted is [object object] but if I console.log my data then I get back the proper data.输出的只是 [object object] 但如果我 console.log 我的数据,那么我会取回正确的数据。
You need to turn the array into a string:您需要将数组转换为字符串:
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>
Please use var modal = "<div class="modal-body">" +JSON.stringify(itemList) +"</div>";
请使用var modal = "<div class="modal-body">" +JSON.stringify(itemList) +"</div>";
JSON.stringify(itemList)
would give you the data inside the object. JSON.stringify(itemList)
将为您提供 object 中的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.