Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

javascript - Convert TD columns into TR rows

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

and I want to translate to:

A 1
B 2
C 3
D 4

??

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

Into this:

<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>

Correct?

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.

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

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 :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...