【发布时间】:2015-05-22 22:32:37
【问题描述】:
我在查找单元格的 ID(及其内容)时遇到了一点问题。主表包含多个分区,每个分区包含一个包含多个单元格的表。我想要的是显示 id content_xx 的单元格。我的表格如下所示:
<table id="MainTable"> // Main (global) table
<div id="divid_1"> // First div in main table
<table id="InfoTable"> // First div's table
<td id="title_10">CellTitle</td> // Cell #1
<td id="content_11">CellContent</td> // Cell #2
<div id="divid_2"> // Second div in main table
<table id="InfoTable"> // Second div's table
<td id="title_20">CellTitle</td> // Cell #1
<td id="content_21">CellContent</td> // Cell #2
// etc...
</table>
查找函数:
function FindContent(id)
{
t = document.getElementById("InfoTable").rows[0].cells.namedItem("content_"+id).innerHTML;
alert(t);
return;
}
我有执行此功能的 onclick 事件。它仅适用于第一个InfoTable,但当我在表#2 或更远的地方尝试相同的东西时它不起作用。我收到此错误:TypeError: document.getElementById(...).rows[0].cells.namedItem(...) is null。我该如何解决这个问题以及为什么它不起作用?是因为row[0]吗?例如,如果我更改为row[1],那么它根本不起作用。我可以改变 html 的结构,但不能完全改变。
【问题讨论】:
-
嗯,我注意到的第一件事是您不止一次使用 id
InfoTable。 ID应该是唯一的。getElementById(..)将始终返回 id 的第一个 encouter。 -
@icecub 哇,这实际上解决了。谢谢。
标签: javascript php html-table row cell