开发者

Make one div containing a table into two divs containing tables

开发者 https://www.devze.com 2023-01-24 09:04 出处:网络
I have a function that gets raw HTML to output开发者_开发知识库 to a table, but I want to take out the first three columns and put them in another div.

I have a function that gets raw HTML to output开发者_开发知识库 to a table, but I want to take out the first three columns and put them in another div.

I am considering making a div on the page that is hidden, setting this div's html to the raw HTML I get, and then using the selector syntax to strip it into each table's div. Is there a way to do this without the intermediate faux-div to hold the raw HTML?


It all depends out what the "function that gets raw HTML" does. Where is it getting the HTML? If it's in some kind of format other than a rendered node, then you should be able to manipulate it as needed prior to rendering it. If you've got it in a string format (and the markup is valid) jQuery is really good at turning strings into traversible objects. For example:

var xml = '<div><span>hello</span></div>';
console.log($(xml).find('span'));

In FireBug, this displays the span as an object node.


I'm not sure exactly why you'd want to do this, rather than arrange your data server-side, but one approach that works is:

$(document).ready(
    function(){
        $('table').click(
            function(){
                $('<table />').appendTo('#newTable').addClass('new');
                $('table').eq(0).find('tr td:first-child').each(
                    function(){
                        $(this).appendTo('.new').wrap('<tr></tr>');
                    });
            });
    });

With the (x)html:

<table>
    <tr>
        <td>1:1</td>
        <td>1:2</td>
        <td>1:3</td>
    </tr>
    <tr>
        <td>2:1</td>
        <td>2:2</td>
        <td>2:3</td>
    </tr>
    <tr>
        <td>3:1</td>
        <td>3:2</td>
        <td>3:3</td>
    </tr>
    <tr>
        <td>4:1</td>
        <td>4:2</td>
        <td>4:3</td>
    </tr>
</table>
<div id="newTable"></div>

JS Fiddle demo

The demo uses jQuery's click() event, but that's just to show it working interactively; it could certainly be placed straight into the DOM-ready/$(document).ready(function(){/* ... */}); event.


The above code would allow repeated clicks (each time moving the first 'column' into a new table), the edit removes that possibility using jQuery's one(), giving the following jQuery:

$(document).ready(
    function(){
        $('table').one('click',
            function(){
                $('<table />').appendTo('#newTable').addClass('new');
                $('table').eq(0).find('tr td:first-child').each(
                    function(){
                        $(this).appendTo('.new').wrap('<tr></tr>');
                    });
            });
    });

JS Fiddle demo, featuring one().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号