简体   繁体   中英

remove an .append() to return an element to it's original state

I'm loading up a ul for a image slider but I need to remove the images ( ul ) and revert back to the original state (before javascript manipulations) when the slider is closed because I will later need to reload the ul for another set of different images.

Here is how I'm loading the slider.

 var get_images = [ "show_1.jpg", "show_2.jpg", "show_3.jpg", "show_4.jpg"];

 $.each(get_images, function(i,img){
 $('#container ul').append('<li><a href="#" class="thumbnail"><img src="'+img+'"/></a></li>'); 
});

I think this might be what you are looking for:

var get_images = ["show_1.jpg", "show_2.jpg", "show_3.jpg", "show_4.jpg"];
var original = $('#container ul').html();
$.each(get_images, function (i, img) {
    $('#container ul').append('<li><a href="#" class="thumbnail"><img src="' + img + '"/></a></li>');
});
$("#revert").click( function() {
    $('#container ul').html(original);
});

The revert button is for demonstration purposes. The idea is basically that you save your original content so that you can revert back to it later if needed.

Fiddle

如果ul最初为空,则可以使用.empty()将其恢复为该状态。

$('#container ul').empty()

How about getting the last one you added and deleting it like this.:

 $('#container ul li:last').remove();

If you have added 3, then repeat that line 3 times. Each one gets the last added element and removes it.


Another way

You can also keep track of what is added with:

var addedList = [];

$.each(get_images, function(i,img){
    var added = $.parseHTML('<li><a href="#" class="thumbnail"><img src="'+img+'"/></a></li>');
    $('#container ul').append(added);
    addedList.push(added);
});

Delete with something like:

for (var i=0; i < addedList.length; ++i) {
    $(addedList[i]).remove();
}
addedList = [];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM