0

I am making an image gallery with a user preference checkbox that displays a large or jumbo size image when the thumbnail is clicked. I have a form element on the page that looks like this:

<input type="checkbox" name="targetbox" id="pref"
    onclick="supersize(this.checked);">
<label for="pref">Supersize Pics</label>

I also have a link and thumbnail like this:

<a href="images/large/image1.jpg"><img src="images/thumbs/image1.jpg" /></a>

The part that is giving me some trouble is the JavaScript. Here is what I was able to cobble together so far:

<script language="JavaScript">
    function supersize(checkme) {
        if (checkme)
            where = "images/super/";
        else
            where = "images/large/";

        for (var i=0; i<=(document.links.length-1); i++) {
            document.links[i].href = where;
        }
    }
</script>

This will replace the links, but not how I need them. Obviously, this will replace the entire href, and I need to retain the "image1.jpg" so the new link would be something like: "images/super/image1.jpg". I am sure I need to use an array or split the url into two parts or something. That's the part I am having trouble figuring out. Any help would be appreciated.

4

3 回答 3

0

我建议使用一个简单的replace()

var href = document.links[i].href;
if (href.indexOf('super') > -1){
    document.links[i].href = href.replace('super','large');
}
else {
    document.links[i].href = href.replace('large','super');
}

当然,这将简单地用字符串替换large字符串super,反之亦然。所以,量身定制if适合自己的。

参考:

于 2012-05-21T23:16:29.460 回答
0

replace()如果您知道最后一个值,则可以使用:

document.links[i].href = document.links[i].href.replace("last/value/goes/here/", where);
于 2012-05-21T23:16:56.297 回答
0

试试这个功能。

hrefLink.lastIndexOf('/')+1获取最后一个“/”的位置,.substr() 获取图像名称,稍后可以将其附加到您想要的任何内容!

<script language="JavaScript">
   function supersize(checkme) {
      if (checkme)
         where = "images/super/";
      else
         where = "images/large/";
      for (var i=0; i<=(document.links.length-1); i++) {
         hrefLink = document.links[i].href;     
         imgName =  hrefLink.substr(hrefLink.lastIndexOf('/')+1);
         document.links[i].href = where+imgName;
      }
   }
</script>

这样,我们在您的上下文中保持函数独立于“super”和“large”等硬编码词。

干杯,哈沙。

于 2012-05-21T23:23:34.113 回答