获取单元格位置 [英] Get Cell Location

查看:95
本文介绍了获取单元格位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个表,当我点击一个 td 我想知道哪个(哪个行和单元格)没有元素上的任何属性。

 < table> 
< tbody>
< tr>
< td> 1< / td>
< td> 2< / td> //如果我点击这个,我想知道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:

 code> //在所有td元素上跟踪onclicks 

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];
//跟踪onclick
cell.onclick = function(){
//跟踪我的位置;
//示例:我在表1中,我是这行的第二个单元格
}
}


解决方案

在处理程序中,这个是表单元格,因此单元格索引执行此操作:

  var cellIndex = this.cellIndex + 1; // + 1是给出一个基于索引的

对于行索引,请执行以下操作:

  var rowIndex = this.parentNode.rowIndex + 1; 

示例: http://jsfiddle.net/fwZTc/1/


So I have this table, and when I click on a td I would like to know where is that(which row and cell) without any attributes on the elements.

<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
    }
}

解决方案

In the handler, this is the table cell, so for the cell index do this:

var cellIndex  = this.cellIndex + 1;  // the + 1 is to give a 1 based index

and for the row index, do this:

var rowIndex = this.parentNode.rowIndex + 1;

Example: http://jsfiddle.net/fwZTc/1/

这篇关于获取单元格位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆