如何选择<td><表格>用javascript? [英] How to select <td> of the <table> with javascript?
问题描述
我知道这是一个非常简单的问题,但我在任何地方都找不到答案.唯一的答案是使用 jQuery 的,而不是纯 JS.我已经尝试了下面的代码,但它不起作用.我不知道为什么.
I know this is very easy question, but I couldn't find the answer anywhere. Only answers are the ones using jQuery, not pure JS. I've tried the code below and it doesn't work. I don't know why.
var t = document.getElementById("table"),
d = t.getElementsByTagName("tr"),
r = d.getElementsByTagName("td");
这也不起作用:
var t = document.getElementById("table"),
d = t.getElementsByTagName("tr"),
r = d.childNodes;
我做错了什么?这样做的最佳方法是什么?
What am I doing wrong? What is the best way to do this?
我确实有我的表的 ID.我知道很傻.这是我的 HTML 的样子:
I indeed have the id of my table table. Preety silly I know. This is how my HTML looks:
<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>
为了更清楚地解释我的意图>我想制作一个井字游戏.首先,我希望点击 <td > 并能够提取该特定的 id <td>.如何最有效地做到这一点?
To explain my intentions more clearly > I wish to make a tic tac toe game. For starters, I wish to click on the < td > and be able extract the id of that particular < td >. How to do it most efficiently?
推荐答案
This d = t.getElementsByTagName("tr")
和 this r = d.getElementsByTagName("td")
都是 数组
.getElementsByTagName
返回一组元素,即使在您的匹配项中只找到一个.
This d = t.getElementsByTagName("tr")
and this r = d.getElementsByTagName("td")
are both arrays
. The getElementsByTagName
returns an collection of elements even if there's just one found on your match.
所以你必须这样使用:
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];
将数组的索引放在要访问对象的位置.
Place the index of the array as you want to access the objects.
请注意,getElementById
顾名思义只是获取具有匹配 id 的元素,因此您的表格必须类似于 <table id='table'>
和getElementsByTagName
通过标签获取.
Note that getElementById
as the name says just get the element with matched id, so your table have to be like <table id='table'>
and getElementsByTagName
gets by the tag.
好吧,继续这篇文章,我认为你可以这样做:
Well, continuing this post, I think you can do this:
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<tds.length;n++)
{
tds[n].onclick=function() { alert(this.innerHTML); }
}
}
试试吧!
这篇关于如何选择<td><表格>用javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!