oFc*_*Fca 13 javascript html-table parent-child
我知道这是一个非常简单的问题,但我无法在任何地方找到答案.只有答案是使用jQuery,而不是纯JS.我已经尝试了下面的代码,它不起作用.我不知道为什么.
var t = document.getElementById("table"),
d = t.getElementsByTagName("tr"),
r = d.getElementsByTagName("td");
Run Code Online (Sandbox Code Playgroud)
这也行不通:
var t = document.getElementById("table"),
d = t.getElementsByTagName("tr"),
r = d.childNodes;
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?做这个的最好方式是什么?
编辑:我确实有我的表格的ID.我知道,我很傻.这就是我的HTML看起来的样子:
<table id="table">
<tr>
<td id="c1">1</td>
<td id="c2">2</td>
<td id="c3">3</td>
</tr>
<tr>
<td id="b1">4</td>
<td id="b2">5</td>
<td id="b3">6</td>
</tr>
<tr>
<td id="a1">7</td>
<td id="a2">8</td>
<td id="a3">9</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
更清楚地解释我的意图>我希望做一个tic tac toe游戏.对于初学者,我希望点击<td>并能够提取特定<td>的ID.如何最有效地做到这一点?
小智 18
这d = t.getElementsByTagName("tr")和这r = d.getElementsByTagName("td")都是arrays.在getElementsByTagName返回元素的集合即使只是一个在你找到匹配.
所以你必须这样使用:
var t = document.getElementById("table"), // This have to be the ID of your table, not the tag
d = t.getElementsByTagName("tr")[0],
r = d.getElementsByTagName("td")[0];
Run Code Online (Sandbox Code Playgroud)
根据需要放置数组的索引以访问对象.
请注意,getElementById正如名称所示,只需获取具有匹配ID的元素,因此您的表必须与标记匹配<table id='table'>并getElementsByTagName获取.
编辑:
好吧,继续这篇文章,我想你可以这样做:
var t = document.getElementById("table");
var trs = t.getElementsByTagName("tr");
var tds = null;
for (var i=0; i<trs.length; i++)
{
tds = trs[i].getElementsByTagName("td");
for (var n=0; n<trs.length;n++)
{
tds[n].onclick=function() { alert(this.id); }
}
}
Run Code Online (Sandbox Code Playgroud)
试试吧!
| 归档时间: |
|
| 查看次数: |
87721 次 |
| 最近记录: |