单击按钮显示JSON

时间:2017-04-11 17:20:21

标签: javascript arrays json

如何通过单击按钮显示随机中的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>

2 个答案:

答案 0 :(得分:1)

这就是你要做的。

  

请注意,您在获取随机数据的逻辑中也存在一些错误。 table ID不存在(已更改为line)且shortname不在您的数据中(已更改为name

&#13;
&#13;
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;
&#13;
&#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>标记中,它应该有效。