1

So basically I have a gallery script in jQuery. When a user clicks on a thumbnail image the image attribute src is then transferred to the main gallery img element. However I now want the user to be able to click a next/prev button and iterate through all the images in the folder. I named them all img0.jpg, img1.jpg and so on. I was thinking I could simply get the current img src via "attr()" and "slice()" then increment the number in the img'0', img'1' etc... with a variable. Heres my code. I hope you guys can understand!

$("#next").click(function () {
   var i = 0;
   var sliceImg = $("#gallerycover").attr("src").slice('0', String.length - 5);
   $("#gallerycover").attr("src", sliceImg + i++ +."jpg");
});
<div id="gallerycontainer">
  <img id="gallery" src="" />
</div>

<div id="thumbcontainer">
  <div id="box4"><img class="thumb" src="" /></div>
</div>
4

3 回答 3

1

尝试替换以下代码:

var sliceImg = $("#gallerycover").attr("src").slice('0', String.length - 5);
$("#gallerycover").attr("src", sliceImg + i++ +."jpg");

对于这个:

var src = $("#gallerycover").attr("src");
var idx = src.indexOf('img');
var sliceImg = src.slice(idx+3, src.length - 4);
$("#gallerycover").attr("src", (parseInt(sliceImg, 10) + 1) + ".jpg");

查看工作演示

于 2013-04-04T21:42:00.280 回答
0
var myInt = 0;
var myInt++;

var sliceImg = $("#gallerycover").attr("src").replace(/\d+/, myInt);

$("#gallerycover").attr("src", sliceImg);
于 2013-04-04T21:44:18.710 回答
0

您可以使用正则表达式来拆分图像源字符串,或者您可以通过向缩略图添加一个属性来让滑块更好地跟踪单个幻灯片,您的下一个/上一个函数可以检查和增加,而无需解析字符串(将来可能会改变)。

于 2013-04-04T21:42:09.310 回答