javascript 从 HTML 中的动态表中获取单元格值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5753503/
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
get cell value from a dynamic table in HTML
提问by Xitrum
I use Javascript to dynamically add new row to a html table, then I used:
我使用 Javascript 将新行动态添加到 html 表中,然后我使用了:
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
queue.innerHTML +=table.rows[rowCount].cells[1].firstChild.nodeValue + "/" + table.rows[rowCount].cells[2].firstChild.nodeValue +"\n";
But it only returned null, thus I wonder that can we get value from cells form row which was dynamically added and how? Thank you.
但它只返回空值,因此我想知道我们可以从动态添加的行中的单元格中获取值吗?谢谢你。
回答by KooiInc
I think the rows
collection is a zero based array like structure. So try using rowCount-1
:
我认为该rows
集合是一个类似结构的基于零的数组。所以尝试使用rowCount-1
:
queue.innerHTML += table.rows[rowCount-1].cells[1].firstChild.nodeValue
+ "/" +
table.rows[rowCount-1].cells[2].firstChild.nodeValue +"\n";
Furthermore, you can use innerText
, as in table.rows[rowCount-1].cells[1].innerText
to get the cell value
此外,您可以使用innerText
, as intable.rows[rowCount-1].cells[1].innerText
来获取单元格值
[edit] skip the rowCount part: you are assigning it before the addition, so rowCount
should work. You should read thisthough, because innerHTML
for tables doesn't always give the desired results.
[编辑] 跳过 rowCount 部分:您在添加之前分配它,所以rowCount
应该工作。不过,您应该阅读此内容,因为innerHTML
对于表格并不总是给出所需的结果。
回答by AndrewR
I don't think nodeValue is the right thing to use. Per thisthe nodeValue of an element is always null.
我不认为 nodeValue 是正确的使用方法。每此元素的的nodeValue总是空。
If you are dynamically creating the table rows, wouldn't it make more sense to add it to queue.innerHTML at the same time instead of doing it this way?
如果您正在动态创建表格行,将它同时添加到 queue.innerHTML 而不是这样做更有意义吗?
回答by Znarkus
Here's how I'd do it with jQuery, if I understand your question correctly.
如果我正确理解您的问题,这就是我将如何使用 jQuery 进行操作。
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript">
var $lastRow = $('table tr:last');
queue.innerHTML += $lastRow.find('td:eq(1)') + '/' + $lastRow.find('td:eq(2)')
</script>
Or :eq(0)
and :eq(1)
if you want the first and second cell.
或者:eq(0)
,:eq(1)
如果您想要第一个和第二个单元格。