3 回答
TA贡献1934条经验 获得超2个赞
所以我不确定你想要做什么,但看看这是否有帮助。这就是我对我认为您正在努力实现的目标的看法:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/bootstrap.min.css">
<meta name="viewport" content="width=device-width, user-scalable=no">
<link rel="stylesheet" href="css/style.css">
<title>Vini Game Store</title>
</head>
<body>
<h1>Games</h1>
<div id = "game1"></br>
<div id = "game2"></br>
<div id = "game3">
<script>
let games = [];//array goes here
var game1 = document.getElementById('game1');
var game2 = document.getElementById('game2');
var game3 = document.getElementById('game3');
game1.innerHTML = games[0].title + ', price:' + games[0].price;
game2.innerHTML = games[1].title + ', price:' + games[1].price;
game3.innerHTML = games[2].title + ', price:' + games[2].price;
</script>
</body>
</html>
TA贡献1860条经验 获得超8个赞
我将使用我通常会做的简化版本,因为我觉得您是 javascript 新手。
我很喜欢将 HTML 和 javascript 分开。通常我会在 HTML 中创建一个模板,克隆它并使用它。我通常也会使用文档片段,所以我只会更新一次 DOM。
为了保持简单,我将使用模板文字并跳过文档片段
var games = [{
title: 'God of War',
price: 50,
img: "./assets/images/God-of-War.jpg"
},
{
title: 'Death Stranding',
price: 70,
img: "./assets/images/Death-Stranding.jpg"
},
{
title: 'The Last Of Us 2',
price: 40,
img: "./assets/images/The-Last-Of-Us-2.jpg"
}
];
function buildGames(parent, games) {
var html = "";
games.forEach(function(game) {
//Set Our Itemp template
let itemTemplate = `
<li>
<h2>${game.title}</h2>
<div class="price">Price: $ ${game.price}</div>
<img src="${game.img}" alt="Image of ${game.title}" />
</li>`;
//update the html
html += itemTemplate
});
//Update the parent once
parent.innerHTML += html;
}
buildGames(document.getElementById("gamesList"), games);
#gamesList {
list-style: none;
padding-left: 0;
}
#gamesList li {
width: 200px;
display: inline-block;
border-radius: 15px;
box-shadow: 2px 2px 4px #333;
margin-right: 5px;
margin-top: 8px;
padding:10px;
}
<h1>Games</h1>
<ul id="gamesList">
</ul>
添加回答
举报