简体   繁体   English

使用 JavaScript 为每个输入 JSON object 创建一个按钮

[英]Creating a button with each input JSON object using JavaScript

I got a situation where I would like to read some data off a JSON format, however I am having some issues understanding how I should construct the button dynamically from JSON object.我遇到了一种情况,我想从 JSON 格式中读取一些数据,但是我在理解如何从 JSON object 动态构建按钮时遇到了一些问题。
My scenario is as follows:我的情况如下:

$(document).ready(function() {
  var socket = io.connect('http://' + document.domain + ':' + location.port);
  // listen for mqtt_message events
  // when a new message is received, log and append the data to the page
  socket.on('mqtt_message', function(data) {
    var json = JSON.parse(data['payload']);
    var table = $("<table>");
    table.append($("<tr><th>Host</th><th>Name</th><th>ID</th><th>"));
    for (var i = 0; i < json.length; i++) {
      var row = $("<tr><td>" + json[i]["name"] +  json[i]["ID"] + "</td></tr>");  
      table.append(row);
    }  
    table.appendTo($("#container"));
  })
});

where在哪里

json = {"host":abc,"name":123,"id":345}

I have to make hostname as button and when I click on that button for example here, name "abc", i will get details name and id in table format.我必须将主机名设置为按钮,当我单击该按钮时,例如在这里,名称为“abc”,我将以表格格式获取详细信息nameid I have created table but it is showing whole table not that scenario which I actually want.我已经创建了表格,但它显示的是整个表格,而不是我真正想要的场景。

I am new to the JavaScript, facing issues here.我是 JavaScript 的新手,在这里遇到问题。

let json = [
    {"host":abc,"name":123,"id":345},
    {"host":def,"name":456,"id":345}
]

In your html write在你的 html 写

<button *ngFor = 'let item of json' (click)='buttonOnClick($event)'>
    {{item.host}}
</button>

Above code will render two buttons for each element in the array上面的代码将为数组中的每个元素呈现两个按钮

In your ts write在你的 ts 中写

buttonOnClick(event) {
    console.log(event) // you will get the corresponding object from the array
}

1) The JSON data doesn't seem to be an array, you can't loop through it. 1) JSON 数据似乎不是一个数组,你不能循环遍历它。

2) You have to append the header to a <thead> element. 2)您必须将 append 和 header 设置为<thead>元素。

3) You have to append the table row to a <tbody> element. 3)您必须将表格行 append 到<tbody>元素。

All tables should have a <thead> and a <tbody> element , so just add it to your HTML code.所有表格都应该有一个<thead>和一个<tbody>元素,所以只需将它添加到您的 HTML 代码中。

 <div id="container">

   <table style="display:none">
     <thead>
       <tr>
         <th>Host</th>
         <th>Name</th>
         <th>ID</th>
       </tr>
     </thead>

     <tbody></tbody>
   </table>

 </div>

Then you append your data to these HTML elements, like so.然后你 append 你的数据到这些 HTML 元素,就像这样。 If your data is an object and not an array, just don't loop through it but instead call the properties as is.如果您的数据是 object 而不是数组,请不要循环遍历它,而是按原样调用属性。

  var json = [{
     host: "Some host IP",
     name: "Some name",
     id: 345
   },
   {
     host: "Some other host IP",
     name: "Some other name",
     id: 987
   }
 ];

 var $container = $("#container");
 var $thead = $("#container table thead");
 var $tbody = $("#container table tbody");
 var $row = $("#container table tbody tr");

 // Loop through items in JSON data..
 json.forEach(function(item) {
   var $button = $("<button>" + item.host + "</button>");
   $container.prepend($button);

     // Button click handler..
   $button.on("click", function() {

     // Replace row HTML..
     $row.html('<td>' + item.host + '</td>' + '<td>' + item.name + '</td>' + '<td>' + item.id + '</td>');

     // Show table if it's not already visible..
     $("#container table").show();

   });
 });



Full code here:完整代码在这里:
https://jsfiddle.net/amsv/15h74uy6/ https://jsfiddle.net/amsv/15h74uy6/


Vanilla JS, ie.香草JS,即。 without jQuery:不带 jQuery:
https://jsfiddle.net/amsv/15h74uy6/72/ https://jsfiddle.net/amsv/15h74uy6/72/

var sampleData = [{ "host": "abc", "name": 123, "id": 345 }, { "host": "xyz", "name": 456, "id": 678 }]

When data is received you should create button which shows table and set data attribute of button with received data.接收到数据后,您应该创建显示表格的按钮并使用接收到的数据设置按钮的数据属性。

for (var i = 0; i < sampleData.length; i++) {
            var item = sampleData[i];
            var button = $('<button />');
            button.text(item.host);
            button.data('data', JSON.stringify(item))
            button.on('click', function (e) {
                e.preventDefault();
                showTable(e);
            });
            $('#buttons').append(button);
        }

showTable is like as below showTable 如下所示

    function showTable(e) {
        var json = JSON.parse($(e.target).data('data'));
        var table = $("<table>");
        table.append($("<tr><th>Host</th><th>Name</th><th>ID</th><th>"));
        var row = $("<tr><td>" + json["host"] + "</td><td>" + json["name"] + "</td><td>" + json["id"] + "</td></tr>");
        table.append(row);
        $("#table").html(table);
    }

Html is below: Html 如下:

    <div id="container">
        <div id="buttons">
        </div>
        <div id="table">
        </div>
    </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM