循环遍历 JSON 数据和 appendChild <TR> 是否将数据放在一行中?

背景:我以为我最终会得到一个动态创建的表,该表具有与<TR>JSON 数据中的条目相同数量的标签。


结果:循环只创建一个表 TR 并将所有数据放在一行中。


下面是循环和表创建的片段。


var tbl = document.createElement("table");

  var tblBody = document.createElement("tbody");

  var row = document.createElement("tr");

    var tdname = document.createElement('td');

    var tddate = document.createElement('td');

    var tdassigned = document.createElement('td');



    for (var i in data) {


    console.log("Hello world!" + i);

    tdname.appendChild(document.createTextNode(data[i].name));

    tddate.appendChild(document.createTextNode(data[i].date));

    tdassigned.appendChild(document.createTextNode(data[i].assigned));

    row.appendChild(tdname);

    row.appendChild(tddate);

    row.appendChild(tdassigned);



    }

    tblBody.appendChild(row);


    tbl.appendChild(tblBody);

    document.getElementById("tasklist").appendChild(tbl);

问题:我需要为每个循环创建一个唯一的行变量吗?


狐的传说
浏览 248回答 3
3回答

当年话下

如果data是对象数组,则从数组方法开始,例如.map()or&nbsp;.forEach()(演示使用,.foreach()因为制作表格实际上并不需要新数组)。这将遍历.insertRow()用于每个对象的数组。现在使用Object.values()or将每个对象转换为其值的元素Object.keys()(演示使用Object.values()它节省了一个步骤)。现在通过值的阵列与迭代.forEach()或.map()和.insertCell()随后.textContent的值到细胞中。let data = [{&nbsp; &nbsp; name: 'John Doe',&nbsp; &nbsp; date: '1/1/19',&nbsp; &nbsp; assigned: 'A'&nbsp; },&nbsp; {&nbsp; &nbsp; name: 'Jane Doe',&nbsp; &nbsp; date: '2/1/819',&nbsp; &nbsp; assigned: 'B'&nbsp; },&nbsp; {&nbsp; &nbsp; name: 'Darth Vader',&nbsp; &nbsp; date: '3/11/19',&nbsp; &nbsp; assigned: 'C'&nbsp; },&nbsp; {&nbsp; &nbsp; name: 'Obi Wan',&nbsp; &nbsp; date: '4/20/19',&nbsp; &nbsp; assigned: 'D'&nbsp; }];const frag = document.createDocumentFragment();const tbl = document.createElement("table");const tblB = document.createElement("tbody");tbl.appendChild(tblB);frag.appendChild(tbl);data.forEach((obj, idx) => {&nbsp; let row = tblB.insertRow();&nbsp; Object.values(obj).forEach(val => {&nbsp; &nbsp; let cell = row.insertCell();&nbsp; &nbsp; cell.textContent = val;&nbsp; });});document.body.appendChild(frag);

一只甜甜圈

我刚刚看到你的评论,你更喜欢 vanilla js。如果有兴趣,这里是 jquery 方式。var data = [&nbsp; &nbsp; { Column1: "col1row1", Column2: "col2row1" },&nbsp; &nbsp; { Column1: "col1row2", Column2: "col2row2" }];$("#tasklist")&nbsp; &nbsp; .append($('<table>')&nbsp; &nbsp; &nbsp; &nbsp; .append($('<tbody>')));var tbody = $("#tasklist > table > tbody");$.each(data, function (idx, item) {&nbsp; &nbsp; $(tbody).append($('<tr>')&nbsp; &nbsp; &nbsp; &nbsp; .append($('<td>')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .text(item.Column1)&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; .append($('<td>')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .text(item.Column2)&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; );});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript