Using JQuery to change order of elements

你。 提交于 2020-01-01 03:15:11

问题


Does anybody know what I'm doing wrong? I'm trying to alter the order on which some images show, I want the images to shift to the right/left one spot every time I hit a button. This is what I've tried but no luck.

Any help or insight will be truly appreciated

$("#rightShift").click(function(){
    $("img").hide();
    var count = $("img").size();
    $("img").each(function(i) { 
        var indexImg = count - i;
        $("img:eq(indexImg)").show();
    });
}); 
$("#leftShift").click(function(){
    $("img").hide();
    $("img:last").prependTo("img");
    $("img").show();
});

回答1:


Assuming you want this to work like a carousel that goes around (the last image become the first one when you are shifting right), then this is how I would do it:

$("#rightShift").click(function(){
    $("img:last").detach().insertBefore("img:first");
});

$("#leftShift").click(function(){
    $("img:first").detach().insertAfter("img:last");
});



回答2:


You're trying to refer to a variable inside a string. That makes no sense.
You actually meant:

$("img:eq(" + indexImg + ")").show();

But a more efficient implementation is:

$(this).prev().show();

The most efficient implementation without side-effects is:

$("#rightShift").click(function(){
    var $images = $("img"); // <-- Reference to all images
    $images.hide();
    //var count = $images.length; //<-- Unused variable, delete it?
    $images.each(function(i) { 
        $(this).prev().show();
    });
}); 
$("#leftShift").click(function() {
    var $images = $("img");
    $images.hide();
    $images.last().prependTo("img"); // OR: $images.before($images.last());
    $images.show();
});



回答3:


This:

$("img:eq(indexImg)").show();

Should be this:

$("img:eq(" + indexImg + ")").show();

Not sure if other stuff is wrong though.



来源:https://stackoverflow.com/questions/9243956/using-jquery-to-change-order-of-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!