3

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

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

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
GCallie
  • 413
  • 1
  • 3
  • 11

1 Answers1

7

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) file and appropriate html tags.

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

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

Community
  • 1
  • 1
kamlesh
  • 154
  • 8
  • 2
    when re-posting a solution, please give credit to the original one: http://stackoverflow.com/a/6298066 – zhirzh Jul 23 '15 at 11:46