开发者

selected tr inside the table

开发者 https://www.devze.com 2023-01-11 13:18 出处:网络
I have a table which has 5 rows. When a user clicks on a TR 开发者_如何转开发I want to know which row was clicked on (I mean the row number, i.e. 2, 3, or 5).

I have a table which has 5 rows. When a user clicks on a TR 开发者_如何转开发I want to know which row was clicked on (I mean the row number, i.e. 2, 3, or 5).

Does anyone know how to do this?


You can do something like this (assuming your table has id="mytable"

// Should use DOM readiness instead of window load,
// but for sake of simplicity i'll use onload here
window.onload = function() {
    var rows = document.getElementById('mytable').getElementsByTagName('tr');
    for (var i = 0; i < rows.length; i++) {
        rows[i].onclick = function() {
            var index = -1;
            for (var j = 0; j < rows.length; j++) {
                if (this == rows[j]) {
                   index = j;
                   break;
                }
            }

            // do something with index (0 = first row .. 4 = 5th row)
        };
    }
};

Alternatively, if you use jQuery, you can just do this:

$(document).ready(function() {
    var $rows = $('#mytable tr');
    $rows.click(function() {
        var index = $rows.index(this);
        // do something with index
    });
});
0

精彩评论

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