【问题标题】:Populate an HTML table with characters from String Array使用字符串数组中的字符填充 HTML 表
【发布时间】:2015-05-10 04:31:26
【问题描述】:

我需要创建一个 2*50 单元格表,并使用预先存储在 JavaScript 数组中的字符串文字填充它。

我已将字符串存储在一个数组中并创建了一个表。我无法填充它。

 //string literal pre-stored in a javascipt array
 var proverbs = ["Love sees no faults", "friend in need is a friend indeed"];
 var txt= proverbs[0];

 document.write('<table id= "tab" border="1" cellspacing="1" cellpadding="30">')
 for(i = 0; i < 50; i++){
    document.write('<tr>')
    document.write('<td>')
    document.write('<td>')
    document.write('</tr>')
 }

 for (i = 0; i < txt.length; i++) {
   tab +=  document.write("<tr><td>" + txt[i] + "</td></tr>");
 } 

 document.write('</table>')

这不起作用。我现在如何填充表格。我写的最后一个 for 循环是填充表格单元格,每个单元格一个字符。谁能告诉我如何实现它。

【问题讨论】:

  • “这不起作用。” - 它有什么作用?还有什么?没有?浏览器控制台中的任何错误? (提示:您在哪里定义了 tab 变量?您使用它但不声明或初始化它。txt 变量是什么 - 只需直接使用 proverbs。)
  • for (i = 0; i " + txt[i] + ""; } .... 这不会填充表格。任何地方都没有错误。但表格仍然是空白的。
  • 如果您使用document.write(…) 编写HTML 标签或使用innerHTML 插入它们并且您不关闭这些标签,那么它们将自动关闭。 IE。 document.write('&lt;table …&gt;') 将生成 &lt;table …&gt;&lt;/table&gt;,其中没有内容。而是将所有标记放在一个字符串中,然后只然后写它。

标签: javascript html arrays html-table


【解决方案1】:

您的代码似乎缺少一些东西。

第一个问题: var prorbs = ["爱看不透", "患难见真情"]; var txt=谚语[0];

您将谚语 sub 0 分配给 txt。没关系,txt 的值现在是“Love see no faults”。但是,稍后您引用 txt[i]。

第二个问题

for (i = 0; i < txt.length; i++) {
  tab +=  "<tr><td>" + txt[i] + "</td>";
}

你没有关闭 tr 标签。但是你也不会对标签做任何事情。

我认为您正在打印一张空表。

【讨论】:

  • 我关闭了该行。我的问题是如何填充表格。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 2017-02-02
  • 1970-01-01
  • 2011-09-07
  • 2023-03-24
  • 2015-11-03
相关资源
最近更新 更多