给表格行添加一个onclick事件
- 论坛
- 给表格行添加一个onclick事件
9 浏览
给表格行添加一个onclick事件
我试图通过Javascript向表行添加一个onclick事件。
function addRowHandlers() { var table = document.getElementById("tableId"); var rows = table.getElementsByTagName("tr"); for (i = 1; i < rows.length; i++) { row = table.rows[i]; row.onclick = function(){ var cell = this.getElementsByTagName("td")[0]; var id = cell.innerHTML; alert("id:" + id); }; } }
在Firefox中,这个代码可以按预期工作,但在Internet Explorer(IE8)中,我无法访问表格的单元格。我相信这与onclick函数中的"this"被识别为"Window"而不是"Table"(或类似的东西)有关。
如果我能访问当前行,我就可以在onclick函数中执行getElementById,但我找不到方法。有什么建议吗?