开发者

Traversing table and returning clicked element's placement

I have an onclick function attached to each <td> element. The function needs to know the placement in the table (row and column).

I found an attribute called rowIndex for <tr>s, but that would involve getting the parent element and still doesn't help with column number.

Here is my function so far (it's within a loop, so it's attaching to every td)

td.onclick = function(event) {
  event = (event) ? event : window.event;
  console.log('rowIndex, colIndex');
}

I could开发者_Python百科 figure this out with jQuery, but I'm trying to do without.


My first thoughts were:

var rows = document.getElementsByTagName('tr');
var cells = document.getElementsByTagName('td');
var cellsPerRow = cells.length/rows.length;
var i = 0;
for (r=0;r<rows.length;r++){
    for (c=0;c<cellsPerRow;c++){
        cells[i].setAttribute('data-col',c + 1);
        cells[i].setAttribute('data-row',r + 1);
        cells[i].onclick = function(){
            var row = this.getAttribute('data-row');
            var col = this.getAttribute('data-col');
            alert('Row: ' + row + '; col: ' + col);
        };
    i++;
    }
}

JS Fiddle demo.

This was then refined to:

var cells = document.getElementsByTagName('td');

for (i=0;i<cells.length;i++){
    cells[i].onclick = function(){
        var row = this.parentNode.rowIndex + 1;
        var col = this.cellIndex + 1;
        alert('Row: ' + row + '; col: ' + col);
    };
}

JS Fiddle demo.


element.cellIndex

will give you the column zero-indexed position.

Example


Is it possible in your situation to echo out the row and column into the td element's id in the server-side script? Such as ...id="' . $row . '_' . $col . '"...

Then it's just a case of parsing the values out from this.id.


Here you go: - http://jsfiddle.net/FloydPink/Lu8Yw/

var tds = document.getElementsByTagName('td');
for (var i = 0; i < tds.length; i++) {
    var td = tds[i];
    td.onclick = function(event) {
        event = (event) ? event : window.event;
        console.log('rowIndex: ' + this.parentNode.rowIndex + ', colIndex: ' + this.cellIndex);
    }
}


First, creating click events for each td is not efficient. Recommend using event delegation. You can google it for the benefits of using Event delegation.

http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/

Basically, the more cells you have in the table, the more memory will be consumed. Instead of creating multiple cells, create one single event to delegate.

var table = document.getElementById('test-table');

table.onclick = function(e) {
    var target = e.target,
        parent;

    if (target.tagName === 'TD') {
        parent = target.parentNode;
        console.log('rowIndex', parent.getAttribute('rowindex'), 'colIndex', target.getAttribute('colindex'));
    }
}

Here is the example in jsfiddle http://jsfiddle.net/EWGzB/1/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜