简体   繁体   中英

Pass Javascript variable to URL

I have a bunch of URL's that automatically load images on a webpage I am developing:

<a href="https://www.sample1.com" target="_blank">
  <img src="https://www.sample1.com" alt="sample1"
<a href="https://www.sample2.com" target="_blank">
  <img src="https://www.sample2.com" alt="sample2">

...

However, some of the images that I need displayed are dynamic and are based on the current time. I know how to get the proper time, hour, and hour in UTC, and then properly define the variable:

<script type="text/javascript">
    
var datee = new Date()
var yyyy = datee.getFullYear()
var mm = datee.getMonth() + 1
var dd = datee.getDate()
var mms = datee.getMinutes()
var hh_UTC = datee.getUTCHours()
var outlook_hour = []   

if (parseInt(hh_UTC) > 0 && parseInt(hh_UTC) < 12){outlook_hour = "0100"}
if (parseInt(hh_UTC) > 11 && parseInt(hh_UTC) < 13){outlook_hour = "1200"}
if (parseInt(hh_UTC) > 13 && parseInt(hh_UTC) < 17){outlook_hour = "1630"}
if (parseInt(hh_UTC) > 16 && parseInt(hh_UTC) < 21){outlook_hour = "2000"}
    
var url1 = "https://sample_img_" + outlook_hour + ".gif"
    
</script>

How am I able to extract the 'url1' variable to have the image load on my page in similar fashion to the first block of code provided? All I could find while searching online is the 'document.getElementbyID' in which I don't really have an 'ID'. Therefore, something along the lines of:

<a href="https://www.updated_img.com" target="_blank">
  <img src=document.getElementbyID(url1) alt="sample_img">

would not work. Therefore, how would I be able to pass the 'url1' variable in the above piece of code to work?

You'll need to give your image an id, and then set the src attribute of it to the value of the variable:

HTML:

<a href="https://www.updated_img.com" target="_blank">
<img id="image1" alt="sample_img">

JavaScript:

window.addEventListener("load", () => {// wait until the page is fully loaded before interacting with the document
  document.getElementById("image1").setAttribute("src", url1);
})

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