Получить ячейку Расположение - PullRequest
6 голосов
/ 15 февраля 2011

Итак, у меня есть эта таблица, и когда я нажимаю на 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
    }
}

Ответы [ 4 ]

18 голосов
/ 15 февраля 2011

В обработчике this - это ячейка таблицы, поэтому для индекса ячейки сделайте это:

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

, а для индекса строки сделайте следующее:

var rowIndex = this.parentNode.rowIndex + 1;

Пример: http://jsfiddle.net/fwZTc/1/

2 голосов
/ 15 февраля 2011

Этот блок скрипта предоставит вам необходимую информацию, добавив информацию в качестве свойств в ячейку и затем получив к ней доступ в функции 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)");
        };
    }
}
1 голос
/ 15 февраля 2011

Ну, когда у вас есть rowspan / colspan, вы можете получить гораздо больше удовольствия, однако, если сетка регулярная, вы можете просто определить свою позицию по индексу, выполнив:

0 голосов
/ 02 ноября 2017

Использование «this» в таблице ячеек

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...