Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - How to invert (transpose) the rows and columns of an HTML table?

I want to transpose the rows and columns in an HTML table, i.e. Rows as Columns, Columns as Rows.

In what way I can do it?

Example :

1 4 7  
2 5 8  
3 6 9

as

1 2 3  
4 5 6  
7 8 9  
question from:https://stackoverflow.com/questions/6297591/how-to-invert-transpose-the-rows-and-columns-of-an-html-table

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

1 Answer

0 votes
by (71.8m points)

http://jsfiddle.net/CsgK9/2/

html:

<table>
    <tr>
        <td>1</td>
        <td>4</td>
        <td>7</td>
    </tr>
    <tr>
        <td>2</td>
        <td>5</td>
        <td>8</td>
    </tr>
    <tr>
        <td>3</td>
        <td>6</td>
        <td>9</td>
    </tr>
</table>


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

js:

$("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;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...