<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="../js/library/jquery/jquery.min.js" type="text/javascript"></script>
<style>
.listContainer {
display: flex;
justify-content: center;
margin-top: 20px;
width: 100%;
}
#grid {
width: 100%;
padding: 0 200px;
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.item {
width: calc(33.33% - 20px);
height: 412px;
background-color: white;
margin-bottom: 20px;
box-shadow: 0 0 6px rgba(0, 0, 0, 0.5);
}
</style>
</head>
<body>
<div class="container">
<div class="listContainer">
<div id="grid">
</div>
</div>
</div>
<script>
const data = [{name:'item1',path:'',txt:''},
{name:'item2',path:'',txt:''},
{name:'item3',path:'',txt:''},
{name:'item4',path:'',txt:''},
{name:'item5',path:'',txt:''},
{name:'item6',path:'',txt:''},];
const grid = document.querySelector('#grid')
data.forEach(item => {
// grid.innerHTML = '<div class="item"><img src="'+item.path+'" alt="">' +
// '<div class="title"></div>' +
// '<div class="from"></div>111</div>';
$('#grid').append('<div class="item"><img src="'+item.path+'" alt="">' +
'<div class="title"></div>' +
'<div class="from"></div>111</div>')
});
</script>
</body>
</html>
以上是部分代码段,当一开始forEach循环使用innerHTML添加页面元素的时候,效果是这样的
只添加了一个元素,其原因是因为grid.innerHTML
会替换掉#grid
元素内部的所有内容,而改用$('#grid').append()
会在#grid
元素内部追加新的内容。所以循环中使用grid.innerHTML
只会保留最后一个元素,而使用$('#grid').append()
会将每次循环的内容都追加到#grid
元素中,从而实现了循环出多个元素的效果。