开发者

Copy list items from one list to another with jQuery

I'm trying to get a list of items from one list and put it into another list.

This is what I have:

$("#change").click(function () {
    arr = $('#old').map(function () {
        return $(this).text();
    }).get();

    $.each(arr, function (index, item) {
        $('#test').append($( "<ul><li>" + item + " at " + index +"</li>" ));
    });
});

HTML:

<ul id="old">
    <li>One</li><li>Two</li><li>Three</li开发者_如何学运维>
</ul>
<ul id="new"></ul>

It would take the items from old and put it in new. It seems that it puts all the items into just one <li> when it puts it in new.


Simply clone() and appendTo() the new list first:

$('#old > li').clone().appendTo('#new');

And then change their text():

$('#new > li').text(function (index, text) {
    return text + ' at ' + index;
});

A working demo: http://jsfiddle.net/vkYUQ/.


Or, combine the above into one statement:

$('#old > li').clone().text(function (index, text) {
    return text + ' at ' + index;
}).appendTo('#new');


$(document).ready(function() {
    $("#change").click(function() {
        var old = $("#old");
        var items = $("#old li");
        var newList = $("#new");
        items.each(function(index, value){
            newList.append(value);
        });
        old.empty();
        return false;
    });
});


You can use data() for copying and store your HTML in data

var $old=$('#old');
$old.data('myhtml',$old.html());

To insert a copy into #test, you can do

var x = $old.data('myhtml');
$(x).appendTo('#test');


Made a fiddle for you to play with:

http://jsfiddle.net/yEgMK/1/

Now, clone() is one way, copying .html() is another, and there may be a few others. Check out the differences in jQuery's API:

http://api.jquery.com/clone/ http://api.jquery.com/html/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜