Добавление onclick события к строке таблицы

Существует очень хорошая немецкая ссылка (и французский язык, я думаю) в selfhtml.org .

26
задан Brian Tompsett - 汤莱恩 26 August 2019 в 10:49
поделиться

4 ответа

Примерно так.

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

РЕДАКТИРОВАТЬ

Рабочая демонстрация .

37
ответ дан 28 November 2019 в 07:18
поделиться

Я думаю, что для IE вам нужно будет использовать свойство srcElement объекта Event . Если вам подходит jQuery, вы можете рассмотреть возможность его использования, поскольку он абстрагирует для вас большинство различий между браузерами. Пример jQuery:

$("#tableId tr").click(function() {
   alert($(this).children("td").html());
});
4
ответ дан 28 November 2019 в 07:18
поделиться

Голова слишком долго застревает в jq. Это будет работать.

function addRowHandlers() {
    var table = document.getElementById("tableId");
    var rows = table.getElementsByTagName("tr");
    for (i = 1; i < rows.length; i++) {
        var row = table.rows[i];
        row.onclick = function(myrow){
                          return function() { 
                             var cell = myrow.getElementsByTagName("td")[0];
                             var id = cell.innerHTML;
                             alert("id:" + id);
                      };
                  }(row);
    }
}
1
ответ дан 28 November 2019 в 07:18
поделиться

Try changing the this.getElementsByTagName("td")[0]) line to read row.getElementsByTagName("td")[0];. That should capture the row reference in a closure, and it should work as expected.

Edit: The above is wrong, since row is a global variable -- as others have said, allocate a new variable and then use THAT in the closure.

0
ответ дан 28 November 2019 в 07:18
поделиться
Другие вопросы по тегам:

Похожие вопросы: