将 TD 列转换为 TR 行 [英] Convert TD columns into TR rows

查看:16
本文介绍了将 TD 列转换为 TR 行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种快速的方法可以将表格 TD 翻译(使用 CSS 或 Javascript)到 TR,目前我有:

Is there a quick way to translate (using CSS or Javascript) a tables TD into TR, currently I have:

A B C D
1 2 3 4

我想翻译成:

A 1
B 2
C 3
D 4

??

推荐答案

你想把HTML这样排列:

You want to turn HTML arranged like this:

<tr><td>A</td><td>B</td><td>C</td><td>D</td></tr>
<tr><td>1</td><td>2</td><td>3</td><td>4</td></tr>

进入这个:

<tr><td>A</td><td>1</td></tr>
<tr><td>B</td><td>2</td></tr>
<tr><td>C</td><td>3</td></tr>
<tr><td>D</td><td>4</td></tr>

正确吗?

您可以使用 Javascript 执行此操作,但是,如果不了解有关站点/HTML 文件结构的更多信息,则很难提出一种方法.我去试试.

You can do this with Javascript, however, it is difficult to suggest a method with out knowing more about the structure of your site/HTML files. I'll give it a go.

假设您的 <table> 标签带有一个 id(像这样:<table id="myTable"> 您可以像这样在 javascript 中访问它:

Assuming your <table> tag comes with an id (like this: <table id="myTable"> you can access it in javascript like this:

var myTable = document.getElementById('myTable');

您可以像这样创建一个新表:

You can create a new table like this:

var newTable = document.createElement('table');

现在您需要将旧表格行转换为新表格列:

Now you need to transpose the old tables rows into the new tables columns:

var maxColumns = 0;
// Find the max number of columns
for(var r = 0; r < myTable.rows.length; r++) {
    if(myTable.rows[r].cells.length > maxColumns) {
        maxColumns = myTable.rows[r].cells.length;
    }
}


for(var c = 0; c < maxColumns; c++) {
    newTable.insertRow(c);
    for(var r = 0; r < myTable.rows.length; r++) {
        if(myTable.rows[r].length <= c) {
            newTable.rows[c].insertCell(r);
            newTable.rows[c].cells[r] = '-';
        }
        else {
            newTable.rows[c].insertCell(r);
            newTable.rows[c].cells[r] = myTable.rows[r].cells[c].innerHTML;
        }
    }
}

这应该可以满足您的需求.预先警告:未经测试.将此 javascript 代码处理到 HTML 页面中作为练习留给读者.如果有人发现我遗漏的任何错误,如果您将它们指出给我或简单地编辑以修复,我会很高兴:)

This ought to do what you need. Be forewarned: not tested. Working this javascript code into an HTML page is left as an exercise for the reader. If anyone spots any errors that I missed, I be gratified if you point them out to me or simply edit to fix :)

这篇关于将 TD 列转换为 TR 行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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