我正在尝试通过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);
};
}
}
Run Code Online (Sandbox Code Playgroud)
这在Firefox中可以正常工作,但在Internet Explorer(IE8)中,我无法访问表格单元格.我认为这在某种程度上与onclick函数中的"this"被识别为"Window"而不是"Table"(或类似的东西)这一事实有关.
如果我可以访问当前行,我可以在onclick函数中执行getElementById,因为我无法找到这样做的方法.有什么建议?
谢谢!