javascript 如何转置 HTML 表格?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24911998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 03:33:57  来源:igfitidea点击:

How to transpose an HTML table?

javascriptjqueryhtml-table

提问by GCallie

Is there a way (I don't know the right word for it) to twist a table with jQuery? With a function or something?

有没有办法(我不知道正确的词)用 jQuery 扭曲表格?用函数什么的?

For example I have an table like this:

例如我有一个这样的表:

<table>
    <tr>
        <th></th>
        <th></th>
        <th></th>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

Table1

表格1

And I want it like this:

我想要这样:

<table>
    <tr>
        <th></th>
        <td></td>
    </tr>
    <tr>
        <th></th>
        <td></td>
    </tr>
    <tr>
        <th></th>
        <td></td>
    </tr>
</table>

enter image description here

在此处输入图片说明

回答by kamlesh

try this code

试试这个代码

<style>
td { padding:5px; border:1px solid #ccc;}
</style>
<script>
$("a").click(function(){
    $("table").each(function() {
        var $this = $(this);
        var newrows = [];
        $this.find("tr").each(function(){
            var i = 0;
            $(this).find("td").each(function(){
                i++;
                if(newrows[i] === undefined) { newrows[i] = $("<tr></tr>"); }
                newrows[i].append($(this));
            });
        });
        $this.find("tr").remove();
        $.each(newrows, function(){
            $this.append(this);
        });
    });

    return false;
});

</script>
<table>
    <tr>
        <td>Heading1</td>
        <td>Heading2</td>
        <td>Heading3</td>
    </tr>

    <tr>
        <td>data</td>
        <td>data</td>
        <td>data</td>
    </tr>
</table>


<p><a href="#">Do it.</a></p>

don't forgot to link necessary (jquery1.6) fileand appropriate html tags.

不要忘记链接必要的 (jquery1.6) 文件和适当的 html 标签。

try give link http://jsfiddle.net/CsgK9/2/

尝试提供链接http://jsfiddle.net/CsgK9/2/

see this link for original view https://stackoverflow.com/a/6298066

请参阅此链接以获取原始视图 https://stackoverflow.com/a/6298066