jQuery交换下一个/上一个图像,数组中的图像 [英] jQuery swap Next/Previous image, images in array
本文介绍了jQuery交换下一个/上一个图像,数组中的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个图像ID的文字数组,我需要在< img src =>
中将它们交换到按钮上的下一个或上一个图像点击事件。初始页面加载时,从 img src
提供的服务器端知道初始当前图像ID。
I have a literal array of image IDs and I need to swap them in <img src="">
to Next or Previous image on buttons click events. The initial current image ID is known from the img src
provided server-side on initial page load.
显然,在交换之前,需要使用目标ID构建URL,如下所示:
Obviously, before swapping, the URL needs to be constructed with the target ID like this:
'http://site.com/images/' + imageID + '.jpg'
我是JS / jQuery的初学者,我想学习正确,简约的方法。 TIA。
I'm a JS/jQuery beginner and would like to learn a correct, minimalistic approach. TIA.
我的代码开始:
var images=["777777","666666","555555"];
var max = $(images).length;
$('#swapnextimg').click{
$("#imageswap").attr('src', ...... );
}
<a id="swapnextimg"></a>
<a id="swapprevsimg"></a>
<div id="imagebox">
<img id="imageswap" src="http://site.com/images/123456.jpg">
</div>
推荐答案
以下是一个例子:
$(function() {
// Image ID array
var images = ['240', '260', '250', '123', '200'];
var max = images.length;
// Get current image src
var curSrc = $('#imageswap').attr('src');
// Find ID in image src
var curID = curSrc.replace(/.*\/(.*?)\.jpg/i, '$1');
var curIdx = 0;
// Search image list for index of current ID
while (curIdx < max) {
if (images[curIdx] == curID) {
break;
}
curIdx++;
}
// For convenience
var imgSrcBase = 'http://placehold.it/';
// Next image on button (and image) click
$('#swapnextimg,#imageswap').click( function() {
curIdx = (curIdx+1) % max;
$("#imageswap").attr('src', imgSrcBase+images[curIdx]+'.jpg');
});
// Prev image on button click
$('#swapprevsimg').click( function() {
curIdx = (curIdx+max-1) % max;
$("#imageswap").attr('src', imgSrcBase+images[curIdx]+'.jpg');
});
});
这篇关于jQuery交换下一个/上一个图像,数组中的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文