追加后删除最后一个元素

时间:2015-04-20 03:16:37

标签: jquery image append element

我有以下内容#maincontent包含一些将加载到#gallery的图片。现在的问题是,如果我点击#maincontent img并将不同的图片加载到#gallery很多次,那么加载就会变得更加眩目和拖延。是因为当我点击下一张图像时,它只是在上一张图像的顶部,而且图像会随着时间的推移堆积起来?我对.append().last()不太熟悉,我只是想知道如何在加载最新图像后删除以前加载的图像。我已经尝试了$('img:last-child', this).remove()但它似乎没有用,所以我只是想知道我是否走在正确的轨道上。

$('#maincontent img').click(function(){
    $myFile = $(this).attr('src');
    $('#gallery').append('<img src="'+$myFile+'" />');
    $('#gallery img').last().css('display','none').fadeIn();

1 个答案:

答案 0 :(得分:0)

.append只需在#gallery内相互添加图片,之后您只需用代码隐藏最后一张图片。这意味着您的页面将加载所有图像,但您只显示最后一个。

但是,如果您只想显示最新图片,只需清除#gallery并添加新图片:

 $('#content').find('img').removeClass('lastitem');//we will add this class to the new image item, so we clear it from the previous images if any

var $image = $('<img class="lastitem"  src="http://armagetron.co.uk/mods/images/sky1.png" />');
$image.hide();//hide the image first
$('#content').append($image);//append the hidden image 

$image.fadeIn(800, function () {//show the image, when it is shown, hide the rest of it 
    $('#content').find('img').not('.lastitem').fadeOut(500, function () {
        $(this).remove();
    });
});

DEMO:https://jsfiddle.net/erkaner/ma6LjfkL/1/

第二种方法:.prevAll

 $('a').click(function () {
    var $image = $('<img class="lastitem"  src="http://armagetron.co.uk/mods/images/sky1.png" />');
    $image.hide();
    $('#content').append($image);

    $image.fadeIn(800, function () {
       $image.prevAll().fadeOut(500, function () {
          $(this).remove();
       });
    });
 })

DEMO:http://jsfiddle.net/erkaner/ma6LjfkL/1/

相关问题