使用JQuery来改变元素的顺序

有人知道我做错了什么吗? 我试图改变某些图像显示的顺序,我希望每次按下按钮时图像都会向右/左移动一个点。 这是我尝试过的但没有运气。

任何帮助或见解都将得到真正的赞赏

$("#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(); }); 

假设你希望这个像旋转木马一样工作(当你向右移动时,最后一个图像成为第一个图像),那么我就是这样做的:

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

您正在尝试引用字符串中的变量。 这是没有意义的。
你的意思是:

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

但更有效的实施是:

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

没有副作用的最有效的实现是:

 $("#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(); }); 

这个:

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

应该是这样的:

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

不确定其他东西是否有问题。