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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19252233/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:53:32  来源:igfitidea点击:

How can I add onclick event to a table column?

javascriptjqueryhtmldomjavascript-events

提问by user2448849

I'm trying to add an onclick event to a table column using JavaScript. For example, an onclick event enabled on the first or second column! The following function is for rows, but I need to edit this function for specific columns.

我正在尝试使用 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);
    }
}

回答by Anand Jha

Try this working soln.

试试这个工作解决方案。

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

工作演示

回答by gwillie

adding class to affected rows/columns would be more flexible.

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

if you know the rows/columns do something like this (untested), for rows 1 and 2:

如果您知道行/列对第 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());
    });

回答by chakroun yesser

This is the code to return row and column number using jQuery, it must be helpful Jsfiddle link

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

$('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);
            });

回答by Stano

You can attach only the single onclickhandler to your table and then recognize the clicked column, this technique is called event delegation:

您可以只将单个onclick处理程序附加到您的表,然后识别单击的列,这种技术称为事件委托

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

JSFiddle 示例