【问题标题】:access the DOM, html table <th> and save table headings into variables.访问 DOM、html 表格 <th> 并将表格标题保存到变量中。
【发布时间】:2014-07-21 20:25:01
【问题描述】:

我需要对 DOM 进行更改。我需要使用段落来呈现表格内容。 为此,我需要获取每行表格的数据。我该怎么做?

<table style="width:300px">
    <tr>
        <th>Name</th>
        <th>Surname</th>
        <th>Age</th>
    </tr>
    <tr>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
    </tr>
    <tr>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
    </tr>
</table>

输出应该是这样的 - Name-Jill, Surname-Smith, Age-50 和 Name-Eve Surname-Jackson Age-94

我写过这样的东西,

  $("table tr").each(function () {
        text = "";
  $(this).find('th').each(function () {
            //save the column headings to variables
        });

        $(this).find('td').each(function () {
            text += $(this).text() + " ";
        });
        alert(text);
    });

它将逐行打印。但需要在每个前面添加 hedings。我想我必须使用数组或类似的东西来存储表格标题并在每个 .

【问题讨论】:

    标签: javascript jquery html dom


    【解决方案1】:

    是的,只需将th 元素的引用存储在变量中,然后逐行遍历其他单元格。您也可以只将标题的文本存储在一个数组中:

    var headings = $('th').map(function() { return $(this).text(); }).get();
    
    $("table tr:has(td)").each(function () {
        var text = "";
        $(this).children('td').each(function (index) {
            text += headings[index] + ":" + $(this).text() + " ";
        });
        alert(text);
    });
    

    【讨论】:

    • 只是想知道:为了访问headings中的数组对象,你不需要链接.get()吗?
    猜你喜欢
    • 1970-01-01
    • 2015-11-23
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-13
    相关资源
    最近更新 更多