简体   繁体   English

将 Javascript 变量传递给 URL

[英]Pass Javascript variable to URL

I have a bunch of URL's that automatically load images on a webpage I am developing:我有一堆 URL 可以自动在我正在开发的网页上加载图像:

<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:我知道如何在 UTC 中获取正确的时间、小时和小时,然后正确定义变量:

<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?我如何能够提取“url1”变量,以与提供的第一个代码块类似的方式在我的页面上加载图像? All I could find while searching online is the 'document.getElementbyID' in which I don't really have an 'ID'.在线搜索时我能找到的只是“document.getElementbyID”,其中我没有真正的“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?因此,我如何能够在上面的代码中传递“url1”变量来工作?

You'll need to give your image an id, and then set the src attribute of it to the value of the variable:你需要给你的图像一个 id,然后将它的src属性设置为变量的值:

HTML: HTML:

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

JavaScript: JavaScript:

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

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

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