简体   繁体   English

如何在 javascript 中添加按钮,因为在 html 表中导入的数据来自 JSON 文件

[英]how to add button in javascript since the data that import in the html table is from JSON file

I am trying to add edit and delete button inside the column but the HTML table was created from JSON file and it is using for loop to print out the content.我正在尝试在列内添加编辑和删除按钮,但 HTML 表是从 JSON 文件创建的,它使用 for 循环打印出内容。 I don't know how to add extra button inside the column (green zone).我不知道如何在列内添加额外的按钮(绿色区域)。

The button that plan to add will be replace in the 'undefined' col.计划添加的按钮将在“未定义”列中替换。

JSON code: JSON 代码:


 [
   {
      "userId":"ravjy", 
      "jobTitleName":"Developer", 
      "firstName":"Ran",
      "lastName":"Vijay",
      "preferredFullName":"Ran Vijay",
      "employeeCode":"H9",
      "region":"DL",
      "phoneNumber":"34567689",
      "emailAddress":"ranvijay.k.ran@gmail.com"
   },
   {
      "userId":"mrvjy",
      "jobTitleName":"Developer",
      "firstName":"Murli",
      "lastName":"Vijay",
      "preferredFullName":"Murli Vijay",
      "employeeCode":"A2","region":"MU",
      "phoneNumber":"6543565",
      "emailAddress":"murli@vijay.com"
      }
   ]
<script>
fetch('employees.json')
  .then(function (response) {
    // The JSON data will arrive here
     return response.json();
  })
    .then(function (data) {
    appendData(data);
  })
  .catch(function (err) {
    // If an error occured, you will catch it here
  });
        
    function appendData(data) {
        
        //Extract Value for HTML HEADER.
        
        var col=[];
        for (var i = 0; i<data.length;i++){
            for (var key in data[i]){
                if (col.indexOf(key) === -1){
                    col.push(key);
                }
            }
        }
        
        //Add edit and delete header
        col.push("Edit","Delete");
        
        // CREATE DYNAMIC TABLE.
        var table = document.createElement("table");

        // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE.
        
        var tr = table.insertRow(-1);                   // TABLE ROW.

        for (var i = 0; i < col.length; i++) {
            var th = document.createElement("th");      // TABLE HEADER.
            th.innerHTML = col[i];
            tr.appendChild(th);
        }
        
           // ADD JSON DATA TO THE TABLE AS ROWS.
        for (var i = 0; i < data.length; i++) {

            tr = table.insertRow(-1);

            for (var j = 0; j < col.length; j++) {
                var tabCell = tr.insertCell(-1);
                tabCell.innerHTML = data[i][col[j]];
                
            }
        }
        
        // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
        var divContainer = document.getElementById("myData");
        divContainer.innerHTML = "";
        divContainer.appendChild(table);
    }
    
   
    
    </script>


  [1]: https://i.stack.imgur.com/YpoDi.png
  [2]: https://i.stack.imgur.com/pu7SB.png

Solution解决方案

Javascript map will help to get that working Javascript map 将有助于使其正常工作

 const data = [ { userId: "ravjy", jobTitleName: "Developer", firstName: "Ran", lastName: "Vijay", preferredFullName: "Ran Vijay", employeeCode: "H9", region: "DL", phoneNumber: "34567689", emailAddress: "ranvijay.k.ran@gmail.com", }, { userId: "mrvjy", jobTitleName: "Developer", firstName: "Murli", lastName: "Vijay", preferredFullName: "Murli Vijay", employeeCode: "A2", region: "MU", phoneNumber: "6543565", emailAddress: "murli@vijay.com", }, ]; function test(type, id) { alert(type + " " + id); } function appendData(data) { //Extract Value for HTML HEADER. data = data.map((item) => { item.Edit_Delete = `<Button type="button" onclick="test('Edit', '${item.userId}')">${item.userId}</Button> <Button type="button" onclick="test('Delete', '${item.userId}')">${item.userId}</Button>`; return item; }); const col = []; for (let i = 0; i < data.length; i++) { for (let key in data[i]) { if (col.indexOf(key) === -1) { col.push(key); } } } //Add edit and delete header // col.push("Edit","Delete"); // CREATE DYNAMIC TABLE. const table = document.createElement("table"); // CREATE HTML TABLE HEADER ROW USING THE EXTRACTED HEADERS ABOVE. let tr = table.insertRow(-1); // TABLE ROW. for (let i = 0; i < col.length; i++) { const th = document.createElement("th"); // TABLE HEADER. th.innerHTML = col[i]; tr.appendChild(th); } // ADD JSON DATA TO THE TABLE AS ROWS. for (let i = 0; i < data.length; i++) { tr = table.insertRow(-1); for (let j = 0; j < col.length; j++) { const tabCell = tr.insertCell(-1); tabCell.innerHTML = data[i][col[j]]; } } // FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER. const divContainer = document.getElementById("myData"); divContainer.innerHTML = ""; divContainer.appendChild(table); } appendData(data);
 <!DOCTYPE html> <html> <body> <div id ="myData"></div> </body> </html>

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

相关问题 如何将数据从 javascript 导入 html 表 - How to import data from javascript to html table 如何将查看/删除按钮添加到从 JSON 数据加载的 HTML 表 - How to add View/Delete button to HTML Table loaded from JSON Data 如何将数据从 XML 文件导入 HTML 表格 - How to import data from XML file to HTML table 如何使用 JavaScript 将 JSON 文件中的图像添加到 HTML - How to add images from a JSON file to HTML using JavaScript 如何使用 PHP 数据库中的数据向基于 JavaScript 的表添加按钮? - How to add button to a JavaScript based Table with Data from PHP Database? 没有javascript的json数据中的html表 - Html table from json data without javascript 我将行添加到html表中,并且添加成功,但是我想将该表数据导入excel表中,如何在下载按钮上添加? - i add row to html table & it added successfully but i want to import that table data to excel sheet how to add on download button? 从json文件导入表格数据时,将“模式”按钮添加到html表格行 - Modal button added to html table rows, while table data is being imported in from json file 如何将动态数据从 json 文件部署到 html 表中? - How deploy dynamic data into html table from json file? 如何将本地 JSON 文件中的数据显示到 HTML 表中? - How to display data from local JSON file to HTML table?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM