简体   繁体   中英

How can I use a checkbox to modify an HREF?

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.

I'd suggest using a simple 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');
}

This will, of course, simply replace the large string with the super string, or vice versa. So, tailor your if to suit.

References:

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

document.links[i].href = document.links[i].href.replace("last/value/goes/here/", where);

Try this function.

hrefLink.lastIndexOf('/')+1 gets the position of the last "/" and .substr() fetches the image name, which can later be appended to whatever you want !

<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>

This way, we keep the function independent of the hard-coded words like "super" and "large" here in your context.

Cheers, Harsha.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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