简体   繁体   English

需要帮助w / JavaScript并从数组创建一个html表

[英]Need help w/ JavaScript and creating an html table from array

I've tried everything I can find via google and nothing has worked correctly. 我已尝试通过谷歌找到的所有内容,但没有任何工作正常。 Output is just a single row with all the contents of the array listed. 输出只是一行,列出了数组的所有内容。 What I need is a way to write the contents of an array but after 3 cells, automatically start a new line. 我需要的是一种编写数组内容的方法,但是在3个单元格之后,自动开始一个新的行。 I'll post the code I've made below as well as the question. 我将发布我在下面提出的代码以及问题。 (yes this is from an assignment. :( ) (是的,这是来自作业。:()

//***(8) place the words in the string "tx_val" in a table with a one pixel border,
//***    with a gray backgound. Use only three cells per row. Empty cells should contain
//***    the word "null". Show the table in the span block with id="ans8"

var count = i % 3;
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
    out += ("<td>" + txArr[i] + "</td>");
    count++;
    if (count % 3 == 0)
    {
        nrow += "</tr><tr>";
    }
}

document.getElementById('ans8').innerHTML = out + nrow;

you need to print the tr 's inside the table (annd add a </table> !): 你需要在表格内打印tr (并添加一个</table> !):

var count = i % 3; // btw. what's this??
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)
{
    out += "<td>" + txArr[i] + "</td>";
    count++;
    if (count % 3 == 0)
        out += "</tr><tr>";
}
out += "</table>";

document.getElementById('ans8').innerHTML = out;

Rather than try to write out the html, try manipulating the dom. 而不是试图写出HTML,尝试操纵dom。 It seems much more straightforward to me. 对我来说似乎更直截了当。 Take a look at the following: 看看以下内容:

var row = table.insertRow(); msdn mdc msdn mdc
var cell = row.insertCell(); msdn mdc msdn mdc
var cellContent = document.createTextNode(txArr[i]); msdn mdc msdn mdc
cell.appendChild(cellContent); msdn mdc msdn mdc

For deciding when to start a new row, just use the modulus operator ( % msdn mdc ) against i : 要决定何时开始新行,只需对i使用模数运算符( % msdn mdc ):

if (i % 3 == 0)
{
    row = table.insertRow()
}

You'd end up with something like this: 你最终得到这样的东西:

var container = document.getElementById("ans8");
var t = container.appendChild(document.createElement("table"));
var row;
txArr.forEach(function (item, i)
{
    if (i % 3 == 0)
    {
        row = t.insertRow()
    }
    row.insertCell().appendChild(document.createTextNode(item));
});

I'll leave a little for you to figure out - border, background color, getting the word "null" in there. 我会留下一点让你弄清楚 - 边框,背景颜色,在那里得到“null”这个词。 It is your homework after all. 毕竟这是你的功课。 :-) :-)

Also, for older browsers you'll need to add Array.forEach in yourself . 此外,对于旧版浏览器,您需要自己添加Array.forEach

It might be a tad easier to accomplish with something like 用类似的东西来完成它可能有点容易

buffer = "<table>";
for(var r = 0; r < 10; r++){
   buffer += "<tr>";
   for(var c = 0; c < 3 ; c++){
      buffer += "<td>Cell: " + r + ":" + c + "</td>";
   }
   buffer += "</tr>";
}
buffer += "</table>";
 document.getElementById("ans8").innerHTML = buffer;

That would create a table 30 rows long by 3 columns for each row. 这将为每行创建一个30行长,3列的表。

you might be assigning values to "count" too early as you don't know what i is yet. 您可能会过早地将值分配给“计数”,因为您不知道我到底是什么。 and you are not spitting out the value of nrow anywhere... change it to out. 并且你没有在任何地方吐出nrow的价值......把它改成了。

var count;
var nrow = "";
var out = "<table border='1' bgcolor='gray'><tr>"
for (var i=0; i<txArr.length; i++)

{
out += ("<td>" + txArr[i] + "</td>");
count++;
if (count % 3 == 0)
    {
    out += "</tr><tr>";
    }
}

 document.getElementById('ans8').innerHTML = out + nrow;

Basically I would split it up into 3 functions, for readability and maintenance. 基本上我会把它分成3个功能,以便于阅读和维护。 These functions would consist of creating a cell, a row, and a table. 这些函数包括创建单元格,行和表格。 This definitely simplifies reading the code. 这肯定简化了阅读代码。 As I have not tested it, below is an example of what I would do. 由于我还没有测试过,下面是我要做的一个例子。

function createTableCell(value) {
  return value == null? "<td>NULL</td>":"<td>" + value + "</td>";
}

function createTableRow(array) {
  var returnValue = "";
  for (var i = 0; i < array.length; i++) {
    returnValue = returnValue + createTableCell(array[i]);
  }
  return "<tr>" + returnValue + "</tr>";
}

function arrayToTable(array, newRowAfterNArrayElements) {
  var returnValue = "<table>";
  for (var i = 0; i < array.length; i = i + newRowAfterNArrayElements) {
     returnValue = returnValue + createTableRow(array.split(i, (i + newRowAfterNArrayElements) - 1));
  }
  return returnValue + "</table>";
}

document.getElementById("ans8").innerHTML = arrayToTable(txArr, 3);

In addition this makes your code much more dynamic and reusable. 此外,这使您的代码更具动态性和可重用性。 Suppose you have an array you want to split at every 4 element. 假设您有一个要在每4个元素拆分的数组。 Instead of hardcoding that you can simply pass a different argument. 而不是硬编码,你可以简单地传递一个不同的参数。

I prefer using an array over concatination 我更喜欢使用阵列而不是连接

var html = [];
html.push("<table><tr>");
var i = 0;

for (var k in txArr)
{
    if(i>=3){
      i=0;
      html.push("</tr><tr>");
    }
    html.push("<td>" + txArr[k] + "</td>");
    i++;
}
html.push("</tr></table>");

document.getElementById('ans8').innerHTML = html.join('');

// wrapped in function
function arrayToTable(a,cols){
 var html = [];
    html.push("<table><tr>");
    var i = 0;

    for (var k in a)
    {
        if(i>=cols){
          i=0;
          html.push("</tr><tr>");
        }
        html.push("<td>" + a[k] + "</td>");
        i++;
    }
    html.push("</tr></table>");
    return html.join('')
}
document.getElementById('ans8').innerHTML = arrayToTable(txArr, 3);

Here's a live example of doing this with DOMBuilder , and of using the same code to generate DOM Elements and an HTML String. 这是使用DOMBuilder执行此操作的实例,并使用相同的代码生成DOM元素和HTML字符串。

Code: 码:

var dom = DOMBuilder.elementFunctions;

function arrayToTable(a, cols) {   
  var rows = [];
  for (var i = 0, l = a.length; i < l; i += cols) {
      rows.push(a.slice(i, i + cols));
  }
  return dom.TABLE({border: 1, bgcolor: 'gray'},
    dom.TBODY(
      dom.TR.map(rows, function(cells) {
        return dom.TD.map(cells);
      })
    )
  );
}

var data = [1, 2, null, 3, null, 4, null, 5, 6];

document.body.appendChild(arrayToTable(data, 3));
document.body.appendChild(
  dom.TEXTAREA({cols: 60, rows: 6},
    DOMBuilder.withMode("HTML", function() {
      return ""+arrayToTable(data, 3);
    })
  )
);

Yes, you can build from scratch...but there's a faster way. 是的,你可以从头开始构建......但是有更快的方法。 Throw a grid at it. 扔一个网格。 The grid will take data in a string, array, json output, etc and turn it into a proper HTML outputted table and will allow you to extend it with sorting, paging, filtering, etc. 网格将采用字符串,数组,json输出等数据并将其转换为正确的HTML输出表,并允许您通过排序,分页,过滤等对其进行扩展。

My personal favorite is DataTables , but there are numerous others out there. 我个人最喜欢的是DataTables ,但还有很多其他的。

Once you get proficient, setting one of these up literally takes 5 minutes. 一旦你熟练,设置其中一个字面需要5分钟。 Save your brain power to cure world hunger, code the next facebook, etc.... 节省你的大脑力量来治愈世界饥饿,编码下一个facebook等等....

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM