将一个onclick事件添加到表行 [英] Adding an onclick event to a table row

查看:70
本文介绍了将一个onclick事件添加到表行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  function addRowHandlers(){
var table = document.getElementById(tableId);
var rows = table.getElementsByTagName(tr); (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,因为我找不到一个方法。任何建议?



谢谢!

解决方案

/ p>

  function addRowHandlers(){
var table = document.getElementById(tableId);
var rows = table.getElementsByTagName(tr); (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);
}
}

编辑



工作演示


I'm trying to add an onclick event to a table row through Javascript.

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);
                      };
    }
}

This works as expected in Firefox, but in Internet Explorer (IE8) I can't access the table cells. I believe that is somehow related to the fact that "this" in the onclick function is identified as "Window" instead of "Table" (or something like that).

If I could access the the current row I could perform a getElementById in the onclick function by I can't find a way to do that. Any suggestions?

Thanks!

解决方案

Something like this.

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);
    }
}

EDIT

Working demo.

这篇关于将一个onclick事件添加到表行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆