Javascript Javascript从html表的特定行中获取列的文本值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10550410/
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
Javascript get the text value of a column from a particular row of an html table
提问by MirrorMirror
A user clicks on a row of a table, and I want to get (in Javascript) the innerhtml of let's say the 3rd column of that row.
用户单击表格的一行,我想获取(在 Javascript 中)假设该行的第 3 列的 innerhtml。
Something like :
就像是 :
document.getElementById("tblBlah").rows[i].columns[j].innerHTML
doesn't seem achievable and I can't find anything here or in the net.
似乎无法实现,我在这里或网上找不到任何东西。
Any solutions would be very much appreciated ( NO jQuery )
非常感谢任何解决方案(没有 jQuery)
回答by Elias Van Ootegem
document.getElementById("tblBlah").rows[i].columns[j].innerHTML;
Should be:
应该:
document.getElementById("tblBlah").rows[i].cells[j].innerHTML;
But I get the distinct impression that the row/cell you need is the one clicked by the user. If so, the simplest way to achieve this would be attaching an event to the cells in your table:
但是我得到的明显印象是您需要的行/单元格是用户单击的行/单元格。如果是这样,实现此目的的最简单方法是将事件附加到表格中的单元格:
function alertInnerHTML(e)
{
e = e || window.event;//IE
alert(this.innerHTML);
}
var theTbl = document.getElementById('tblBlah');
for(var i=0;i<theTbl.length;i++)
{
for(var j=0;j<theTbl.rows[i].cells.length;j++)
{
theTbl.rows[i].cells[j].onclick = alertInnerHTML;
}
}
That makes all table cells clickable, and alert it's innerHTML. The event object will be passed to the alertInnerHTML
function, in which the this
object will be a reference to the cell that was clicked. The event object offers you tons of neat tricks on how you want the click event to behave if, say, there's a link in the cell that was clicked, but I suggest checking the MDN and MSDN (for the window.event object)
这使得所有表格单元格都可以点击,并提醒它是innerHTML。事件对象将被传递给alertInnerHTML
函数,其中该this
对象将是对单击的单元格的引用。事件对象为您提供了大量关于您希望单击事件如何表现的巧妙技巧,例如,如果单击了单元格中的链接,但我建议检查 MDN 和 MSDN(对于 window.event 对象)
回答by Phuc Nguyen Minh
in case if your table has tbody
如果你的桌子有 tbody
let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)