【问题标题】:How to insert array values into a HTML table with javascript?如何使用 javascript 将数组值插入到 HTML 表中?
【发布时间】:2020-08-13 07:36:12
【问题描述】:

我正在尝试使用 javascript 函数将数组放入 HTML 表中,但我不知道如何插入该数组?这个想法是当我点击按钮插入时,它会将一个人的信息添加到行中。 This's my table

   <script>
        //Array
        var a = [
            {name:"Micheal", age:20, hometown:"New York"},
            {name:"Santino", age:25, hometown:"Los Angeles"},
            {name:"Fredo",   age:29, hometown:"California"},
            {name:"Hagen",   age:28, hometown:"Long Beach"},
        ]

        //Insert data function
        function Insert_Data() {
          var table = document.getElementById("myTable");
          //Help......  
        }

    </script>
<!--Button Insert-->
    <input type="button" onclick="Insert_Data" value="Insert" /> 
    <!--Table-->
    <table id="myTable">
        <tr>
            <th>Full Name</th>
            <th>Age</th>
            <th>Country</th>
        </tr>

        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>

        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>

        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>

        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>

    </table>

【问题讨论】:

    标签: javascript html arrays html-table


    【解决方案1】:

    你同时声明了thead和tbody,并在函数中循环填充表格

    var a = [
        {name:"Micheal", age:20, hometown:"New York"},
        {name:"Santino", age:25, hometown:"Los Angeles"},
        {name:"Fredo",   age:29, hometown:"California"},
        {name:"Hagen",   age:28, hometown:"Long Beach"},
    ]
    
    //Insert data function
    function Insert_Data() {
      var table = document.getElementById("datas");
      table.innerHTML="";
      var tr="";
      a.forEach(x=>{
         tr+='<tr>';
         tr+='<td>'+x.name+'</td>'+'<td>'+x.age+'</td>'+'<td>'+x.hometown+'</td>'
         tr+='</tr>'
    
      })
      table.innerHTML+=tr;
      //Help......  
    }
    <input type="button" onclick="Insert_Data()" value="Insert" /> 
    <!--Table-->
    <table id="myTable">
        <thead>
           <tr>
            <th>Full Name</th>
            <th>Age</th>
            <th>Country</th>
        </tr>
        </thead>
       <tbody id="datas">
    
       </tbody>
    
    
    
    </table>

    【讨论】:

      【解决方案2】:

      单击按钮创建一个动态元素tr和td,并将​​其附加到文档中的table元素中。

      使用https://www.w3schools.com/jsref/met_node_appendchild.asp 作为参考来了解如何创建动态元素。

      【讨论】:

        【解决方案3】:

        这是一个完全通用的方法,你可以添加一个新的键,它会在数据中添加一个新的列,没问题:

        //Array
        var myData = [
            {name:"Micheal", age:20, hometown:"New York", example: "extra"},
            {name:"Santino", age:25, hometown:"Los Angeles", example: "extra"},
            {name:"Fredo",   age:29, hometown:"California", example: "extra"},
            {name:"Hagen",   age:28, hometown:"Long Beach", example: "extra"},
        ]
        
        //get references to the table and the head and body:
        const myTable = document.getElementById('myTable');
        const myTable_header = myTable.querySelector('thead')
        const myTable_body = myTable.querySelector('tbody')
        
        //Insert data function
        function Insert_Data() {
          //Help...... :
          myTable_header.innerHTML = '';
          var tr = document.createElement('tr');
          const headers_data = Object.keys(myData[0]);
          headers_data.forEach((key) => {
            var th = document.createElement('th')
            th.innerHTML = key
            tr.appendChild(th);
          })
          myTable_header.appendChild(tr);
          myTable_body.innerHTML = '';
          for (let i = 0; i < myData.length; i++){
            var tr = document.createElement('tr');
            headers_data.forEach((key) => {
              var td = document.createElement('td');
              td.innerHTML = myData[i][key]
              tr.appendChild(td);
            });
            myTable_body.appendChild(tr);
          }
        }
        <!--Button Insert-->
        <input type="button" onclick="Insert_Data()" value="Insert" /> 
        <!--Table-->
        <table id="myTable">
          <thead>
            <!-- Data is injected here -->
          </thead>
          <tbody>
            <!-- Data is injected here -->
          </tbody>
        </table>

        【讨论】:

          【解决方案4】:

          演示证明:https://jsfiddle.net/psw41g6k/

          function Insert_Data() {
                   var table = document.getElementById("myTable");
                   var rows = table.querySelectorAll('tr');
                   console.log(rows)
                   for (let i = 1; i < rows.length; i++) {
                     rows[i].children[0].textContent = a[i-1].name
                     rows[i].children[1].textContent = a[i-1].age
                     rows[i].children[2].textContent = a[i-1].hometown
                   }
          
                 }
          

          【讨论】:

            【解决方案5】:

            如果您要经常更改数组,对于动态表

            let tableBody = a.reduce((rows, nextRow) =>{
                            return rows += 
                                '<tr>' + 
                                Object.keys(nextRow).reduce((cols, nextCol) => { 
                                    return cols += '<th>' + nextRow[nextCol] + '</th>'
                                }, '') + 
                                '</tr>'
                        }, '')
            

            【讨论】:

              猜你喜欢
              • 2021-03-25
              • 2013-05-06
              • 1970-01-01
              • 1970-01-01
              • 2018-06-06
              • 1970-01-01
              • 1970-01-01
              • 2014-05-10
              • 2019-09-07
              相关资源
              最近更新 更多