Javascript从html表格的特定行中获取列的文本值 [英] Javascript get the text value of a column from a particular row of an html table
问题描述
用户点击表格的一行,我想获得(用Javascript)innerhtml,让我们说这一行的第三列。
Something如:
document.getElementById(tblBlah)。rows [i] .columns [j] .innerHTML
似乎不可行,我在这里或网上找不到任何东西。
任何解决方案都将非常值得赞赏(NO jQuery)
的document.getElementById( tblBlah)行[I] .columns [j]的.innerHTML。
应该是:
的document.getElementById( tblBlah)行[I] .cells [j]的.innerHTML。
但是我明显地看到您需要的行/单元格是用户点击的行/单元格。如果是这样,最简单的方法就是将一个事件附加到表格中的单元格中:
function alertInnerHTML(e)
{
e = e || window.event; // IE
alert(this.innerHTML);
}
var theTbl = document.getElementById('tblBlah'); (var j = 0; j (var i = 0; i {
)
{
theTbl.rows [i] .cells [j] .onclick = alertInnerHTML;
$ b $ p
$ b 这使得所有表格单元都可点击,并提醒它的innerHTML 。事件对象将被传递给 alertInnerHTML
函数,其中 this
对象将是对单元格的引用被点击。事件对象提供了大量巧妙的技巧,说明如果单击单元格中存在链接时,您希望单击事件的行为方式,但我建议检查MDN和MSDN(对于window.event对象) p>
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.
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 )
解决方案 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)
这篇关于Javascript从html表格的特定行中获取列的文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!