如何将onclick事件添加到表列?

时间:2013-10-08 15:40:44

标签: javascript jquery html dom javascript-events

我正在尝试使用JavaScript将onclick事件添加到表列。例如,在第一列或第二列上启用了onclick事件!以下函数适用于行,但我需要为特定列编辑此函数。

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

4 个答案:

答案 0 :(得分:2)

尝试这个工作溶解。

function addRowHandlers() {
 var table = document.getElementById("tableId");
 var rows = table.getElementsByTagName("tr");

 for (i = 0; i < rows.length; i++) {
    var currentRow = table.rows[i];
    currentRow.onclick = createClickHandler(currentRow);
 }
}

function createClickHandler(row){

            return function() { 
                   var cell = row.getElementsByTagName("td")[0];// if you put 0 here then it will return first column of this row
                       var id = cell.innerHTML;
                        alert("id:" + id);
              };

}

addRowHandlers();

<强> Working Demo

答案 1 :(得分:1)

将类添加到受影响的行/列会更灵活。

如果您知道行/列执行类似这样的操作(未经测试),则对于第1行和第2行:

var $table = jQuery('#tableId');
var $rows = jQuery('tr:nth-child(0),tr:nth-child(1)', $table);
$rows
    .addClass('event-1')
    .click(function()
    {
      // do what on click event
      alert(jQuery(this).html());
    });

答案 2 :(得分:1)

这是使用jQuery返回行号和列号的代码,它必须有用 Jsfiddle link

$('td').on('click',function() {
                var col = $(this).parent().children().index($(this));
                var row = $(this).parent().parent().children().index($(this).parent());
                alert('Row: ' + row + ', Column: ' + col);
            });

答案 3 :(得分:0)

您只能将单个onclick处理程序附加到表中,然后识别单击的列,此技术称为event delegation

document.getElementById("tableId").onclick = columnHandler;

function columnHandler(e) {
    e = e || window.event; //for IE87 backward compatibility
    var t = e.target || e.srcElement; //IE87 backward compatibility
    while (t.nodeName != 'TD' && t.nodeName != 'TH' && t.nodeName != 'TABLE') {
        t = t.parentNode;
    }
    if (t.nodeName == 'TABLE') {
        return;
    }
    var c = t.parentNode.cells;
    var j = 0;
    for (var i=0; i<c.length; i++){
        if (c[i] == t) {
            j = i;
        }
    }
    alert('You clicked on row #'+(j+1)+ ' , cell content = '+t.innerHTML);
}

JSFiddle example

相关问题