可以'我不明白为什么;t将行和单元格添加到表中

can't figure out why this doesn't add row and cell to table

本文关键字:单元格 添加 为什么 明白 可以      更新时间:2023-09-26

当我运行脚本时,控制台中没有任何错误,只是不会添加行和单元格。当找到多行结果时,我需要添加一行和单元格。我有错误吗????这是的一小部分代码

var txt = "";
var i = 0;                   
for (state in stateMiles) {
    i++;
    var x =(stateMiles[state]);
   (stateMiles[state])= parseFloat(x);  
    function appendRow() {
        var tbl = document.getElementById("table"), // table reference
            row = tbl.insertRow(tbl.rows.length),      // append table row
            i;
        // insert table cells to the new row
        for (i = 0; i < tbl.rows[0].cells.length; i++) {
            createCell(row.insertCell(i), i, 'row');
        }
    }
    $("#results").append
    $(".state" + i).append(state);
    $(".mile" + i).append(stateMiles[state]);
}

您的代码片段一团糟。您是否在for循环中声明了一个函数?

不要那样做。

这是像Angular、React等MVC风格库都非常擅长的事情,但如果你想做到这一点,这里有一些代码应该会有所帮助。

<script type="text/javascript">
$(function() {
  
  var stateMiles = [
    {
      state: "CO",
      miles: 5082
    },
    {
      state: "TX",
      miles: 582085
    },
    {
      state: "IL",
      miles: 9852
    }
  ];
  
  var tbody = $( "#my_table tbody" );
  for( state_idx in stateMiles ) {
    
    var state = stateMiles[ state_idx ];
    tbody.append( $( "#row_template" ).html().replace( "{{state}}", state.state ).replace( "{{miles}}", state.miles ) );
    
  }
  
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
  <body>
    <table id="my_table">
      <thead>
        <th>State</th>
        <th>Miles</th>
      </thead>
      <tbody>
        
      </tbody>
    </table>
    
    <script type="text/html" id="row_template">
      <tr>
        <td>{{state}}</td>
        <td>{{miles}}</td>
      </tr>
    </script>
  </body>
</html