简体   繁体   English

向 JavaScript 随机图像数组中的图像添加超链接

[英]Adding Hyperlinks to Images in a JavaScript Random Images Array

I have a random image generating array and I am hoping to insert hyperlinks associated with each image but I can't seem to find an answer or solution that works;我有一个随机图像生成数组,我希望插入与每个图像关联的超链接,但我似乎找不到有效的答案或解决方案; or that I can understand enough to adapt to my situation/code.或者我可以理解到足以适应我的情况/代码。 I am a javascript novice just trying to learn as much as I can as I go, Thanks in advance to any help, all is appreciated!我是 javascript 新手,只是想尽可能多地学习 go,在此先感谢您的帮助,不胜感激!

JS as follows: JS如下:

var random_images_array = ['img1.jpg', 'img2.jpg', 'img3.jpg'];

    
function getRandomImage(imgAr, path) {
    path = path || 'img/'; // default path here
    var num = Math.floor( Math.random() * imgAr.length );
    var img = imgAr[ num ];
    var imgStr = '<img src="' + path + img + '" alt = "">';
    document.write(imgStr); document.close();
}

HTML: HTML:

<div id="heroImage" style="text-align: center">
        <script type="text/javascript">getRandomImage(random_images_array, 'img/heroImage/')</script>
</div>

Here's what I think you're trying to accomplish.这就是我认为你正在努力实现的目标。 Note: don't use document.write -- that has very specific uses and this isn't a good one.注意:不要使用 document.write——它有非常特定的用途,这不是一个好用的。 Rather use the innerHTML property (and there are other ways too).而是使用 innerHTML 属性(还有其他方法)。 I modified the code so you could see the result in the snippet.我修改了代码,以便您可以在代码段中看到结果。

 let random_images_array = [{ img: "https://picsum.photos/200/300?1", link: "https://google.com" }, { img: "https://picsum.photos/200/300?2", link: "https://yahoo.com" }, { img: "https://picsum.photos/200/300?3", link: "https://loren.picsum.com" } ]; function getRandomImage(imgAr, path) { path = path || 'img/'; // default path here path = ''; // JUST FOR SO TESTING let num = Math.floor(Math.random() * imgAr.length); let img = path + imgAr[num].img; let imgStr = `<a href='${imgAr[num].link}'><img src="${img}" alt="" border="0" /></a>`; document.querySelector('#heroImage').innerHTML = imgStr; } window.addEventListener('DOMContentLoaded', () => { getRandomImage(random_images_array, 'img/heroImage/') })
 <div id="heroImage" style="text-align: center"> </div>

picsum answers GETs from picsum.photos/width/height by redirecting to a random image with the requested dimensions. picsum.photos/width/height通过重定向到具有请求尺寸的随机图像来回答来自 picsum.photos/width/height 的 GET。

In order to have the image and the link match, you must make the picsum GET request and get the redirect URL from the response "Location" header.为了使图像和链接匹配,您必须发出 picsum GET 请求并从响应“位置”header 中获取重定向 URL。 That's the URL that should be placed in the DOM.那就是应该放在 DOM 中的 URL。

After running the snippet, right-click the image and open it in new tab.运行代码片段后,右键单击图像并在新选项卡中打开它。 Note the same image appears.请注意出现相同的图像。 Using the original GET url as the href will direct user to a new random image.使用原始的 GET url 作为 href 将引导用户到一个新的随机图像。

 // super simple promise-returning http request async function get(url) { return new Promise(resolve => { const xmlHttp = new XMLHttpRequest(); xmlHttp.addEventListener("load", () => resolve(xmlHttp)); xmlHttp.open("GET", url); xmlHttp.send(); }); } async function getRandomImage(width, height) { const url = `https://picsum.photos/${width}/${height}`; let res = await get(url); // this is the important part: we need the redirect url for the image const redirectURL = res.responseURL const html = `<a href='${redirectURL}' target='_blank'><img src="${redirectURL}" alt=""/></a>`; const el = document.querySelector('#heroImage') el.innerHTML = html; } getRandomImage(200, 300)
 <div id="heroImage" style="text-align: center"> </div>

Notice that we don't need to fool around with a random pick from an array of URLs.请注意,我们不需要从一组 URL 中随机挑选。 picsum does the randomizing on the initial GET. picsum 在初始 GET 上进行随机化。

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

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