如何通过单击按钮显示随机中的JSON对象。使用Javascript。
sysconf(_SC_PAGESIZE)
HTML代码: 以下是显示值的按钮代码。
var myObject = {
"catalogo": [
{
"id" : "001",
"name":"Nike",
"desc" : "shoes",
"price": 500,
},
{
"id" : "002",
"name":"MIKEY",
"desc" : "shoes",
"price": 500,
},
{
"id" : "003",
"name":"VANS",
"desc" : "shoes",
"price": 500,
},
{
"id" : "004",
"name":"SPORT",
"desc" : "shoes",
"price": 500,
}
]
};
var random = myObject.catalogo[Math.floor(Math.random()* myObject.catalogo.length)];
document.getElementById('table').innerHTML = random.shortname + "<br>" + "$" + random.price + ".00";
我想在这里展示
<div>
<div id="random"></div>
<button>Añadir</button>
</div>
答案 0 :(得分:1)
请注意,您在获取随机数据的逻辑中也存在一些错误。
table
ID不存在(已更改为line
)且shortname
不在您的数据中(已更改为name
)
var myObject = {
"catalogo": [{
"id": "001",
"name": "Nike",
"desc": "shoes",
"price": 500,
},
{
"id": "002",
"name": "MIKEY",
"desc": "shoes",
"price": 500,
},
{
"id": "003",
"name": "VANS",
"desc": "shoes",
"price": 500,
},
{
"id": "004",
"name": "SPORT",
"desc": "shoes",
"price": 500,
}
]
};
function showRandom() {
var random = myObject.catalogo[Math.floor(Math.random() * myObject.catalogo.length)];
document.querySelector('.line').innerHTML = random.name + "<br>" + "$" + random.price + ".00";
}
&#13;
<div>
<div id="random"></div>
<button onclick="showRandom()">Añadir</button>
</div>
<div>
<p class="line"></p>
</div>
&#13;
答案 1 :(得分:0)
将您的button
更改为<button id="anadir">Añadir</button>
。
执行此操作后,您可以在文档加载后从JS获取按钮:
window.addEventListener("DOMContentLoaded", function(event) {
var myAddButtton = document.getElementById('anadir');
myAddButton.onclick = function() {
var random = myObject.catalogo[
Math.floor(Math.random()* myObject.catalogo.length)
];
document.querySelector('.line')
.innerHTML = random.shortname + "<br>" + "$" + random.price + ".00";
}
}
将其加载到页面的<script>
标记中,它应该有效。