获取单元格位置
问题描述:
所以我有这张表格,当我点击td
时,我想知道元素中没有任何属性的地方(哪一行和哪一个单元格)。获取单元格位置
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td> // If I click on this I would like to know tr:1 & td:2
<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>
</tbody>
</table>
的Javascript:
// Track onclicks on all td elements
var table = document.getElementsByTagName("table")[0];
var cells = table.getElementsByTagName("td"); //
for(var i = 1; i < cells.length; i++){
// Cell Object
var cell = cells[i];
// Track with onclick
cell.onclick = function(){
// Track my location;
// example: I'm in table row 1 and I'm the 2th cell of this row
}
}
答
在处理程序,this
是表格单元格,因此对于细胞指数做到这一点:
var cellIndex = this.cellIndex + 1; // the + 1 is to give a 1 based index
和行索引,这样做:
var rowIndex = this.parentNode.rowIndex + 1;
答
好,当你有ROWSPAN/COLSPAN你可以有更多的乐趣,但是,如果电网正常,你可以决定从索引你的位置由这样做的:
row = Math.floor(i/rows);
column = i % columns;
答
这个脚本块将为您提供通过将信息作为属性的单元格您想要的信息,然后在onclick
函数中访问它们:
// Track onclicks on all td elements
var table = document.getElementsByTagName("table")[0];
// Get all the rows in the table
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
//Get the cells in the given row
var cells = rows[i].getElementsByTagName("td");
for (var j = 0; j < cells.length; j++) {
// Cell Object
var cell = cells[j];
cell.rowIndex = i;
cell.positionIndex = j;
cell.totalCells = cells.length;
cell.totalRows = rows.length;
// Track with onclick
console.log(cell);
cell.onclick = function() {
alert("I am in row " + this.rowIndex + " (out of " + this.totalRows + " rows) and I am position " + this.positionIndex + " (out of " + this.totalCells + " cells)");
};
}
}
答
使用 “这种” 对细胞表
function myFunction(x) {
var tr = x.parentNode.rowIndex;
var td = x.cellIndex;
document.getElementById("tr").innerHTML = "Row index is: " + tr;
document.getElementById("td").innerHTML = "Column index is: " + td;
}
tr, th, td {
padding: 0.6rem;
border: 1px solid black
}
table:hover {
cursor: pointer;
}
<table>
<tbody>
<tr>
<td onclick="myFunction(this)">1</td>
<td onclick="myFunction(this)">2</td>
<td onclick="myFunction(this)">3</td>
</tr>
<tr>
<td onclick="myFunction(this)">4</td>
<td onclick="myFunction(this)">5</td>
<td onclick="myFunction(this)">6</td>
</tr>
<tr>
<td onclick="myFunction(this)">7</td>
<td onclick="myFunction(this)">8</td>
<td onclick="myFunction(this)">9</td>
</tr>
</tbody>
</table>
<p id="tr"></p>
<p id="td"></p>
jQuery有很有帮助[`$的.index()`](http://api.jquery.com/index/)方法,该方法如果你对框架开放,可以为你做这件事。 – Sampson 2011-02-15 00:54:15
我不想使用任何框架,但我会尝试查看jQuery中该功能的功能。 – Adam 2011-02-15 00:55:38