Click table row and get value of all cells

后端 未结 5 946
温柔的废话
温柔的废话 2020-12-31 16:05

I don\'t know JQuery, so I\'m hoping there is a way to do this in pure Javascript.

I need to click on a table row and get the value of each cell in that row. Here i

5条回答
  •  太阳男子
    2020-12-31 16:45

    There is no need to add ids or add multiple event handlers to the table. One click event is all that is needed. Also you should use thead and tbody for your tables to separate the heading from the content.

    var table = document.getElementsByTagName("table")[0];
    var tbody = table.getElementsByTagName("tbody")[0];
    tbody.onclick = function (e) {
        e = e || window.event;
        var data = [];
        var target = e.srcElement || e.target;
        while (target && target.nodeName !== "TR") {
            target = target.parentNode;
        }
        if (target) {
            var cells = target.getElementsByTagName("td");
            for (var i = 0; i < cells.length; i++) {
                data.push(cells[i].innerHTML);
            }
        }
        alert(data);
    };
    OCB Area Name Cell # Nickname
    275 Layton Installation Benjamin Lloyd (801) 123-456 Ben

    Example:

    http://jsfiddle.net/ZpCWD/

提交回复
热议问题