Javascript Javascript获取表格行TR的单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5620646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:05:48  来源:igfitidea点击:

Javascript get cells of a table row TR

javascripthtmldom

提问by Ervin

I want to manipulate table cells with javascript, and so far I managed to get into tr-s, by using:

我想用 javascript 操作表格单元格,到目前为止我设法进入 tr-s,通过使用:

var as = document.getElementById('answers['+id+']');
var trs = as.getElementsByTagName("tr");
for (var i in trs)
{ ... }

UPDATE: The asvariable contains a reference to the table.

更新:该as变量包含对表的引用。

Inside of the for cycle I wanted to go on the same login line and I have tried:

在 for 循环内,我想在同一登录行上进行,并且尝试过:

var tds = trs[i].getElementByTagName("td");

The problem is that on debugging I get the following error:

问题是在调试时我收到以下错误:

Uncaught TypeError: Object #<HTMLTableRowElement> has no method 'getElementByTagName' .

How could I get into the td-s of the tr-s?

我怎么能进入 tr-s 的 td-s?

回答by Sangeet Menon

its getElementsByTagNameand not getElementByTagName

getElementsByTagName而不是getElementByTagName

var as = document.getElementById('answers['+id+']');
for(var i=0;i<as.rows.length;i++) {
    var trs = as.getElementsByTagName("tr")[i];
    var cellVal=trs.cells[0]
}

the variable cellValwill give the reference to the first cellor <td>similarly do for all the cells by increasing the index or putting it in a loop would make it dynamic...

该变量cellVal将通过增加索引或将其放入循环中来为所有单元格提供对第一个cell<td>类似操作的引用将使其动态...

回答by niksvp

Check spelling of the method you are using to get td i.e.getElementByTagName

检查您用来获取 td 的方法的拼写,即getElementByTagName

It should be getElementsByTagName. This should work fine as the way you are trying to fetch.

应该是getElementsByTagName。按照您尝试获取的方式,这应该可以正常工作。

Check Manipulating the table with DOM and CSSfor more info.

查看使用 DOM 和 CSS 操作表格以获取更多信息。