我设置了一个本地存储项,一个数组更准确。
然后我得到它并尝试填充我的文字模板,但我得到一个未定义
undefined:1在未定义时获取http://localhost/undefined 404(未找到):1
这是我的代码:
var rawRelatedProductCategoryArray = localStorage.getItem('relatedCategoryProductsSelected');
var parsedRelatedProductArray = ('rawRelatedProductCategoryArray', JSON.parse(rawRelatedProductCategoryArray));
console.log(parsedRelatedProductArray); // on this i get the result of my array
document.getElementById("relatedProducts").innerHTML = `${parsedRelatedProductArray.map(relatedProductsTemplate).join('')}`
这是我试图将数组数据放入其中的模板:
function relatedProductsTemplate(relatedProduct) {
return `
<div class="relatedDiv">
<div class="item mb-0 text-center ">
<div>
<div class="post-prev-img">
<a href="#"><img src="${relatedProduct.image}" alt="img"></a>
</div>
<div class="post-prev-title mb-5">
<h3><a class="font-norm a-inv" href="shop-single.html">${relatedProduct.dataProduct}</a></h3>
</div>
<div class="shop-price-cont">
<strong>${relatedProduct.price}</strong>
</div>
</div>
</div>
</div>
`
}
我发现我做错了什么:
问题是因为数组是嵌套的。
所以我喜欢这样:
var arrayNesting = parsedRelatedProductArray[0];
然后我将var传递给文字,如下所示:
document.getElementById("relatedProducts").innerHTML =
`${arrayNesting.map(relatedProductsTemplate).join('')}`