문제

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

다른 팁

If the ul was initially empty you can use .empty() to get it back to that state.

$('#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 = [];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top