Convert TD columns into TR rows

后端 未结 4 789
时光取名叫无心
时光取名叫无心 2020-11-28 12:42

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

4条回答
  •  半阙折子戏
    2020-11-28 12:55

    You want to turn HTML arranged like this:

    ABCD
    1234
    

    Into this:

    A1
    B2
    C3
    D4
    

    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

    tag comes with an id (like this:
    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 :)

    提交回复
    热议问题