在HTML中动态地向表添加行

时间:2016-06-06 13:17:21

标签: javascript php html

如何通过从网页获取这些行的数据来自动向HTML表添加新行。

<table class="sortable">
    <thead>
        <tr>
            <th>Foldername</th>
            <th>Subfolder</th>
        </tr>
    </thead>
    <tbody>
        <tr class='$class'>
           <td><span id="albumname"></span></td>
           <td><span id="subdirname"></span></td>              
        </tr>
    </tbody>
</table>

Foldername和Subfolder是标题,无需更改它们,但albumname和subdirname必须按每行的相应值更改。

我使用websocket获取数据:

 $.get("http://localhost:8040/api/album", function (data) {
            console.log("data: ", data);
            var i;
            var j;
            console.log(i);
            for (i = 0; i < data.length; i++) {
                console.log("start for loop");
                var albname = data[i].Name;
                console.log("albname: ", albname);
                $("#albumname").text(albname);
                var subalbum = data[i].SubAlbums
                for (j = 0; j < subalbum.length; j++) {
                    var subname = data[i].SubAlbums[j];
                    console.log("SubName: ", subname);
                    $("#subdirname").text(subname);
                }
            }
        });

1 个答案:

答案 0 :(得分:3)

像这样添加一个类<body>

<tbody class="tableBody">

</tbody>

并按照以下方式更新您的jQuery代码,假设每个专辑都有多个子目录名称。

$.get("http://localhost:8040/api/album", function (data) {
      var i;
      var j;
      $('.tableBody').html('');
      for (i = 0; i < data.length; i++) {
        console.log("start for loop");
        var albname = data[i].Name;

        var bodyTr=$('<tr>');

        var albumNameTd=$('<td>');
        albumNameTd.text(albname);

        var subDirNameTd=$('<td>');
        var subDirHtml="";

        var subalbum = data[i].SubAlbums;

        for (j = 0; j < subalbum.length; j++) {
          var subname = data[i].SubAlbums[j];
          subDirHtml+=subname;
          if(j!=subalbum.length-1) {
                subDirHtml+="<br>";
          }
        }
        subDirNameTd.html(subDirHtml);
        bodyTr.append(albumNameTd);
        bodyTr.append(subDirNameTd);
        $('.tableBody').append(bodyTr);
      }
});