单击表格行并获取所有单元格的值 [英] Click table row and get value of all cells

查看:41
本文介绍了单击表格行并获取所有单元格的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不懂 JQuery,所以我希望有一种方法可以在纯 Javascript 中做到这一点.

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 is the format of my table:

<table class='list'>
    <tr>
        <th class='tech'>OCB</th>
        <th class='area'>Area</th>
        <th class='name'>Name</th>
        <th class='cell'>Cell #</th>
        <th class='nick'>Nickname</th>
    </tr>
    <tr onclick="somefunction()">
        <td>275</td>
        <td>Layton Installation</td>
        <td>Benjamin Lloyd</td>
        <td>(801) 123-456</td>
        <td>Ben</td>
    </tr>
</table>

无论如何都不能为每个单元格设置一个唯一的 ID 吗?

Is there anyway short of putting a unique ID to each cell?

推荐答案

无需向表中添加 id 或添加多个事件处理程序.只需要一个点击事件.此外,您应该对表格使用 thead 和 tbody 以将标题与内容分开.

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

<table class='list'>
    <thead>
        <tr>
            <th class='tech'>OCB</th>
            <th class='area'>Area</th>
            <th class='name'>Name</th>
            <th class='cell'>Cell #</th>
            <th class='nick'>Nickname</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>275</td>
            <td>Layton Installation</td>
            <td>Benjamin Lloyd</td>
            <td>(801) 123-456</td>
            <td>Ben</td>
        </tr>
    </tbody>
</table>

示例:

http://jsfiddle.net/ZpCWD/

这篇关于单击表格行并获取所有单元格的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆