我正在研究以下演示。如何每天将[day-1, day-2, day-3, day-3]
中的<span>
名玩家每天加载/追加到.card-body
中?因此,在这种情况下,只需加载四个card-body
。
var cars = {
"day-1": {
"player-1-1": "Ford",
"player-1-2": "BMW"
},
"day-2": {
"player-2-1": "Benz",
"player-2-2": "KIA",
},
"day-3": {
"player-3-1": "Toyota",
"player-3-2": "Mazda",
},
"day-4": {
"player-4-1": "Honda",
"player-4-2": "Nissan",
},
}
Object.getOwnPropertyNames(cars).forEach((val, index) => {
var txt = Object.values(cars[val]);
console.log(txt);
})
span {
background: orange;
color: #fff;
display: inline-block;
float: left;
padding: 12px;
margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
<div class="card-body"></div>
答案 0 :(得分:0)
只需将HTML字符串附加到正文:
var cars = {
"day-1": {
"player-1-1": "Ford",
"chapter-1-2": "BMW"
},
"day-2": {
"player-2-1": "Benz",
"player-2-2": "KIA",
},
"day-3": {
"player-3-1": "Toyota",
"player-3-2": "Mazda",
},
"day-4": {
"player-4-1": "Honda",
"player-4-2": "Nissan",
},
}
Object.getOwnPropertyNames(cars).forEach((val, index) => {
var txt = Object.values(cars[val]);
document.body.innerHTML += `<div class="card-body">${txt}</div>`;
});
span {
background: orange;
color: #fff;
display: inline-block;
float: left;
padding: 12px;
margin: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
如果要使用按键day-1
,day-2
等代替车名,只需将倒数第二行的txt
替换为val
。
document.body.innerHTML += `<div class="card-body">${val}</div>`;
答案 1 :(得分:0)
根据需要使用Javascript / jQuery添加<div class="card-body"></div>
:
这是一个例子:
我在您的HTMl
代码中添加了一个ID为id的div:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="result"></div>
在您的Javascript
代码中:
var tds = new Array();
var j = 0;
Object.getOwnPropertyNames(cars).forEach((val, index) => {
var txt = Object.values(cars[val]);
tds[++j] = "<div class='card-body'>";
tds[++j] = "<p>"+ txt.split(',')[0] +"</p>"
tds[++j] = "<p>"+ txt.split(',')[1] +"</p>"
tds[++j] = "</div>";
});
$("#result").append(tds.join(''));
您已完成。
我使用了jack-bashford提供的代码来访问JSON对象而不进行测试。但这是另一个问题,您可以希望解决。