Существует очень хорошая немецкая ссылка (и французский язык, я думаю) в selfhtml.org .
Примерно так.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
РЕДАКТИРОВАТЬ
Рабочая демонстрация .
Я думаю, что для IE вам нужно будет использовать свойство srcElement объекта Event . Если вам подходит jQuery, вы можете рассмотреть возможность его использования, поскольку он абстрагирует для вас большинство различий между браузерами. Пример jQuery:
$("#tableId tr").click(function() {
alert($(this).children("td").html());
});
Голова слишком долго застревает в jq. Это будет работать.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 1; i < rows.length; i++) {
var row = table.rows[i];
row.onclick = function(myrow){
return function() {
var cell = myrow.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
}(row);
}
}
Try changing the this.getElementsByTagName("td")[0])
line to read row.getElementsByTagName("td")[0];
. That should capture the row
reference in a closure, and it should work as expected.
Edit: The above is wrong, since row is a global variable -- as others have said, allocate a new variable and then use THAT in the closure.