简体   繁体   中英

html/javascript: using a variable as url for <a href>

I developed a html page with a bit of javascript. I have several tags and after clicking a link one of them is dynamically assigned a background image. This url is stored in a global variable. So far so good.

var picture,thumb

function changeDivs(p)
{
     if (p!='') {
        picture = './images/p'+p+'.jpg'; // global url variable
        thumb = './thumbs/p'+p+'.jpg'; // global url variable
        var pic = "url("+thumb+")";
        document.getElementById("poster").style.backgroundImage = pic;
        }
}

I call the function like this:

<a href="javascript:changeDivs('2')">Link</a>

Now I want to make use of a thumbnailviewer script which needs to be accessed like this:

<a href="javascript: global variable" rel="thumbnail"> <!-- Of course this "javascript: global variable" should be a valid url: the stored 'picture' variable -->
        <div id="poster"> 
        </div>
    </a>

So I have stored the url in variable: picture

How can I access the thumbnailviewer script through <a href> AND use the variable. I don't know if the thumbnail script can be called through a function or how.

Thanks a lot!

I think this is what you are attempting to achieve. Here is the jsfiddle .
When an '<a href>' is clicked an image becomes the background of "<div id='poster'>"

I replaced your pic's URL with your existing thumbnail url. Please make sure your picture and thumb variable's URL exist. Also, i set width and height of your poster's div.

To work with thumbnailviewer, try the new jsfiddle link please. FYI, dynamicdrive blocked jsfiddle from accessing the js files. Please try the code on your own project.

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