如何将对应的表头(th)复制到其表单元格(td)? [英] How can I copy the corresponding table header (th) to their table cell (td)?

查看:237
本文介绍了如何将对应的表头(th)复制到其表单元格(td)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将表的< th> 内容复制到 <td> 单元格的相应属性.

I want to copy the <th> contents of a table to the corresponding attributes of the <td> cells.

我的桌子是这样的:

<table>
    <thead>
        <tr>
            <th>Heading 1</th>
            <th>Heading 2</th>
            <th>Heading 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Lorem</td>
            <td>lipsum</td>
            <td>dolor</td>
        </tr>
    </tbody>
</table>

这是我要实现的目标:

<table>
    <thead>
        <tr>
            <th>Heading 1</th>
            <th>Heading 2</th>
            <th>Heading 3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td data-attr="Heading 1">Lorem</td>
            <td data-attr="Heading 2">lipsum</td>
            <td data-attr="Heading 3">dolor</td>
        </tr>
    </tbody>
</table>

我尝试过此操作,但不起作用:

I tried with this, but it doesn't work:

var $th = $("thead td");
var $td = $("tbody td")

var $th = $td.closest('table').find('th').eq($td.index());
$td.attr("data-attr", $th);

jsFiddle

在我的自定义属性中,我得到了data-attr="[object Object]"文本.

In my custom attribute I get data-attr="[object Object]" insted of th text.

推荐答案

获取标题条目,然后对于每一行,获取每个td并使用其索引从匹配的标题条目中获取文本.有多种方法可以做到这一点.

Get the header entries, then for each row, get each td and use its index to get the text from the matching header entry. There are multiple ways to do this.

长版:

var $th = $("thead th");
var $tr = $("tbody tr");
$tr.each(function(){
    $(this).find('td').each(function(index){
        $(this).attr('data-attr', $th.eq(index).text());
    });
});

JSFiddle:: http://jsfiddle.net/TrueBlueAussie/pLdzx6wm/

另一种方法(快一点)是使用标头元素的索引,并将文本立即应用于所有匹配列TD:

Another way (slightly faster) is to use the index of the header elements and apply the text to all of the matching columns TDs at once:

var $th = $("thead th");
var $tr = $("tbody tr");
$th.each(function(index){
    $tr.find('td:nth-child(' + index + ')').attr('data-attr', $(this).text());
});

JSFiddle:: http://jsfiddle.net/TrueBlueAussie/pLdzx6wm/1/

最后,您可以使用相当酷的jQuery功能,可以将大多数参数替换为回调函数以返回值:

And lastly, you can use the rather cool jQuery feature that most parameters can be replaced with a callback function to return the value:

var $th = $("thead th");
var $tr = $("tbody tr");
$tr.each(function (index) {
    $('td', this).attr('data-attr', function () {
        return $th.eq($(this).index()).text();
    });
});

JSFiddle:: http://jsfiddle.net/TrueBlueAussie/pLdzx6wm/3/

将以下内容减少一些:

var $th = $("thead th");
$('tbody tr td').attr('data-attr', function () {
    return $th.eq($(this).index()).text();
});

JSFiddle:: http://jsfiddle.net/TrueBlueAussie/pLdzx6wm/4/

这篇关于如何将对应的表头(th)复制到其表单元格(td)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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