简体   繁体   English

如何通过将1递增添加到img src使用javascript(jQuery&iviewer)更改图像?

[英]How can I change an image using javascript (jQuery & iviewer) by adding 1 to the img src incrementally?

Checked various questions on SO, but found nothing that quite matches what I'm after... 在SO上检查了各种问题,但没有发现与我的要求完全匹配的内容...

I'm buildling an image viwer using a combination of jQuery and iViewer . 我正在使用jQuery和iViewer的组合来构建图像浏览器。 Here's the code that's used to call different images in iviewer: 这是用于在iviewer中调用不同图像的代码:

$("#chimg").click(function()
{
   iv1.iviewer('loadImage', "img/01.jpg");
   return false;
});

As can be seen, I've named the images sequentially. 可以看出,我已经依次命名了图像。 Right now, all the images are called using individual links, one per image, but ideally I'd like to be able to add previous and next image buttons as well. 现在,所有图像都使用单独的链接调用,每个图像一个链接,但是理想情况下,我也希望能够添加上一个和下一个图像按钮。

Since the images are sequentially named, I was wondering if there was a method of calling the next image in a sequence by adding the value of '1' to the current image? 由于图像是按顺序命名的,因此我想知道是否存在一种通过将'1'的值添加到当前图像来依次调用下一个图像的方法吗? Obviously, I'm happy to change the naming conventions of the files if this is necessary. 显然,如果有必要,我很高兴更改文件的命名约定。

(Disclaimer: I'm a fast learner, but I'm also new to javascript. Solutions that are talked through would really be preferred...) (免责声明:我是一个学习速度很快的人,但是我也是javascript新手。经过讨论的解决方案真的是首选...)

This should do the trick... 这应该可以解决问题...

var i = 0;

$("#chimg").click(function()
{
    i++;
    iv1.iviewer('loadImage', "img/" + ("0" + i).slice(-2) + ".jpg");
    return false;
});

This... 这个...

("0" + i).slice(-2)

...adds 0 to the beginning of whatever value is stored in i and then takes the last 2 characters, so you've got your 0 padded number. ...将0存入i中存储的任何值的开头,然后采用最后2个字符,因此您的填充数字为0。

i have never used iViewer before but first option off the top of my head is can you get the 'src' attribute for the img? 我以前从未使用过iViewer,但最重要的选择是您可以获取img的'src'属性吗? if you have the source you can get the number via regular expression 如果您有来源,则可以通过正则表达式获取数字

var src = $('#chimg').attr('src');
var m = parseInt(src.match(/\d+/g));
n = m+1;
src = src.replace(m, n);
iv1.iviewer('loadImage', src);

then whatever else you have to do. 然后您要做的其他任何事情。

see it work 看到它的工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM