我有一个有5行的表。当用户点击TR时,我想知道点击了哪一行(我的意思是行号,即2,3或5)。
有谁知道怎么做?
答案 0 :(得分:1)
你可以这样做(假设你的桌子有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)
};
}
};
或者,如果你使用jQuery,你可以这样做:
$(document).ready(function() {
var $rows = $('#mytable tr');
$rows.click(function() {
var index = $rows.index(this);
// do something with index
});
});