HTML和简单的JS(没有react / vue)。我需要做一个列表卡,并希望做一个循环,以避免重复的html。
当前代码:
<div id="products-cards-container">
<div class="products-cards">
<div class="product-header">
<img src="../assets/img/image1.png"/>
</div>
<div class="product-content">
<h4>title 1</h4>
<p>super content 1</p>
</div>
<button class="info-button">+ info</button>
</div>
<div>
<div class="product-header">
<img src="../assets/img/cards/products/image2.png"/>
</div>
<div class="product-content">
<h4>title 2</h4>
<p>super content 2</p>
</div>
<button class="info-button">+ info</button>
</div>
<div>
<div class="product-header">
<img src="../assets/img/cards/products/image-3.png"/>
</div>
<div class="product-content">
<h4>title 3</h4>
<p>blablablablbalbalbabla blablaba</p>
</div>
<button class="info-button">+ info</button>
</div>\
</div>
我正在尝试返回html
script.js
const valuesCards = [
{
image: '../img/image1.png',
title: 'title 1',
content: 'super content 1',
},
{
image: '../img/image2.png',
title: 'title 2',
content: 'super content 2'
},
{
image: '../img/image-3.png',
title: 'title3',
content: 'blablablablbalbalbabla blablaba'
},
]
创建一个函数,将卡片列表插入.products-cards div中:
function returnCards() => {
----- AND HERE I AM STUCK
(as well, all tries I did with a simple array / object returned only the last info) ----
}
4条答案
按热度按时间0h4hbjxa1#
使用
Array.prototype.map
函数和模板文字。kx1ctssn2#
你可以这样做
bd1hkmkf3#
mwkjh3gx4#
您需要执行一个“for循环”,迭代valuesCards对象,并为每个值返回一个html模板,然后注入到DOM中所需的元素中。
例如:
重要提示!!在要打印卡片的html中创建id=“products-cards-container”的div元素。