3

onclickJavaScript を使用してテーブル列にイベントを追加しようとしています。たとえばonclick、1 列目または 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];
        var createClickHandler = function (row) {
            return function () {
                var cell = row.getElementsByTagName("td")[0];
                var id = cell.innerHTML;
                alert("id:" + id);
            };
        };

        currentRow.onclick = createClickHandler(currentRow);
    }
}
4

4 に答える 4

3

このワーキングソルンを試してみてください。

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

ワーキングデモ

于 2013-10-08T15:54:51.250 に答える
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());
    });
于 2013-10-08T16:36:09.007 に答える
1

これは、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);
            });
于 2013-10-09T09:54:59.430 に答える
0

単一のハンドラーのみをテーブルにアタッチ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 の例

于 2013-10-08T17:24:25.123 に答える