获取表属性的最后一行

时间:2012-03-07 21:28:35

标签: javascript dom

var table = document.getElementById(table1);
var lastRow = table.rows.length;

var country = lastRow.getElementById('Country');
country.setAttribute('class', "Country"+lastRow);   

我很新,我想知道这是否可行?

而不是

var Country= document.getElementById('Country');

因为我有其他id =国家,因为我正在添加新行..

修改

我知道身份证是独一无二的。但我克隆了最后一行,所以当然ID都是一样的。

4 个答案:

答案 0 :(得分:9)

可以从rows属性访问表的最后一行。

var lastRow = table.rows[ table.rows.length - 1 ];

但是我认为对于你究竟要求的内容存在一些疑惑。

答案 1 :(得分:2)

以下是如何隐式获取最后一个单元格。请注意,您可以使用方括号表示法引用行或单元格数组中的特定对象,并且由于数组索引从0开始,您必须从长度中减去1以将其用作有效的最后一个索引。

此示例显示了您可以执行的一些操作:

<!DOCTYPE html>
<html>

<head>
<title>Table test</title>

<script language="javascript" type="text/javascript">

function init() {

var table = document.getElementById("table1");

var lastRowIndex = table.rows.length-1;

var lastCellIndex = table.rows[lastRowIndex].cells.length-1;

alert( table.rows[lastRowIndex].cells[lastCellIndex].innerHTML ); // alerts the cell's containing HTML, or 9

var lastCell = table.rows[lastRowIndex].cells[lastCellIndex]; // contains a reference to the last cell

}



window.onload = init;
</script>

</head>

<body>


<table id="table1">
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>4</td><td>5</td><td>6</td></tr>
<tr><td>7</td><td>8</td><td>9</td></tr>
</table>


</body>

</html>

假设您有一个包含8列和4行的任意表,如下例所示,并希望第5列和第3行中的单元格获取您想要获取对表的引用的单元格(例如通过{ {1}})然后通过getElementByIdrows选择正确的行和列,确保减去1,因为数组索引从0开始。请参阅此示例:

cells

答案 2 :(得分:2)

我认为最好的方法是:

var lastTr = document.getElementById('tabRecapCommande').lastElementChild.lastElementChild;

document.getElementById('tabRecapCommande')返回<table> document.getElementById('tabRecapCommande').lastElementChild。返回<tbody> document.getElementById('tabRecapCommande').lastElementChild.lastElementChild <tr>

<tbody> console.log(lasTr)

如果您<tr>,您会看到上一个JsonModel元素:)

答案 3 :(得分:1)

HTML文档中的ID是唯一的。因此,不需要进行子查询以便找到元素。而是始终使用document.getElementById('Country')

相关问题