简体   繁体   English

在JavaScript数组中向图像添加超链接

[英]Adding hyperlink to image in javascript array

I found some topics on this, but none really answered my question as they had the array implemented differently. 我找到了一些与此相关的主题,但是没有一个人真正回答了我的问题,因为他们对数组的实现方式有所不同。

I have this javascript array with images and two buttons next and previous. 我有这个带有图像的javascript数组,以及上一个和下一个按钮。 I want to add hyperlinks to the pictures in the array so that when I cycle through them via the buttons I can click them and enter mentioned sites. 我想向数组中的图片添加超链接,以便当我通过按钮循环浏览它们时,可以单击它们并输入提到的站点。

The HTML is as follows: HTML如下:

<div id="leftbox">
<p id="leftpopis"> Whats new on the web? </p>
<img src="obrazky/0.png" id="imgDemo" > 
<button onclick="prvs()" id="btnTwo"> <img src="obrazky/left.png"/> 
</button> 
<button onclick="nxt()" id="btnOne"> <img src="obrazky/right.png"/> 
</button>

And the javascript also as follows: 而javascript也如下:

<script>
var img = new 
Array("obrazky/0.png","obrazky/1.png","obrazky/2.png","obrazky/3.png");

var imgElement = document.getElementById("imgDemo");
var i = 0;
var imgLen = img.length;

    function nxt()
    {
        if(i < imgLen-1)
            {
                i++;
            }
        else{
                i=0;                
            }

            imgElement.src = img[i];                    
    }

    function prvs()
    {
        if(i > 0)
            {
                i--;
            }
        else
        {
            i = imgLen-1;
        }
            imgElement.src = img[i];                    
    }

It is functional, such that it switches the pictures but when I want to add something like this to the array: 它是有功能的,因此它可以切换图片,但是当我想向数组中添加类似内容时:

var img = new Array Array("<a href="comments.html"> obrazky/0.png"</a>);

It doesn't work. 没用 Has someone any idea, how to update the array so it works as intended? 有人知道如何更新数组以使其按预期工作吗?

At first glance, I may be missing other things, but it looks like you are accidentally exiting your string and also not fully including the anchor tag. 乍一看,我可能会漏掉其他东西,但看起来您不小心退出了字符串,并且还没有完全包含锚标记。

var img = new Array("<a href="comments.html"> obrazky/0.png"</a>);

You have a couple options here. 您在这里有几个选择。 You can use single-quotes (and include your a tag) like this 您可以使用单引号(并注明您的标签 )这样

var img = new Array("<a href='comments.html'> obrazky/0.png</a>");

or I think you can use a literal string here using the backtick (under the ~squiggly) 或者我认为您可以在此处使用反引号使用文字字符串(在〜squiggly下)

var img = new Array(`<a href="comments.html"> obrazky/0.png</a>`);

Create a object with the images and the urls maybe? 用图像和URL创建对象吗?

[{img: "obrazky/0.png", url: "comments.html"}, {...}, {...}]

imgElement.src   = img[i.img];
linkElement.href = img[i.url];

I see what you're trying to do. 我知道你在做什么。 I'd recommend loading your content beforehand but in this example you have I'd recommend using an object opposed to an array. 我建议事先加载您的内容,但在本示例中,我建议使用与数组相对的对象。 Or even an array of objects. 甚至是一组对象。 So: 所以:

var img = [
    {
        "img": "obrazky/0.png",
        "href": "comments.html",
    },
    {
        "img": "obrazky/0.png",
        "href": "comments.html",
    }
];

You can access the properties as such img[i].img and img[i].href . 您可以访问img[i].imgimg[i].href

So in your current setup you wanna do something like: 因此,在您当前的设置中,您想执行以下操作:

<a href="" id="imageAnchor"><img id="imgDemo" src=""></a>

And set your data with 然后用

document.getElementById("imageAnchor").href = img[i].href;
document.getElementById("imgDemo").src = img[i].img;

BUT as I said previously, a better method would be to load your images beforehand and cycle through them. 但正如我之前所说,更好的方法是预先加载图像并循环浏览。

<ul id="images">
    <li class='active'><a href="comments.html"><img src="obrazky/2.png"></a></li>
    <li><a href="comments.html"><img src="obrazky/1.png"></a></li>
    <li><a href="comments.html"><img src="obrazky/0.png"></a></li>
</ul>

<style>
    ul#images {
        margin:0px;
        padding:0px;
        list-style-type:none;
    }
    ul#images li {
        display:none;
    }
    ul#images li:first-child,
    ul#images li.active {
        display:block;
    }
</style>

<script>
     imageContainer = document.getElementById("images");

     document.getElementById("btnOne").addEventListener(function(event) {
         event.preventDefault();
         //do magic here.
         //been a while since I've touched vanilla so give me a minute :d
         //basically what you need to do here is cycle through the nodes, 
         //find the active one, if there is a nextSibling of .active:
         // set nextSibling.class ='active' and the current element remove active
         for(var i=0; i < imageContainer.childNodes.length; i++) {
             if (imageContainer.childNodes[i].className == 'active') {
                  if (imageContainer.childNodes[i].nextSibling !== 'undefined') {
                      imageContainer.childNodes[i].nextSibling.className = 'active';
                      imageContainer.childNodes[i].className = '';
                  }
              }
         }
     };

     //Notice this function is similar and I've replaced nextSibling with Previous for the opposite direction 

     document.getElementById("btnTwo").addEventListener(function(event) {
         event.preventDefault();

         for(var i=0; i < imageContainer.childNodes.length; i++) {
             if (imageContainer.childNodes[i].className == 'active') {
                  if (imageContainer.childNodes[i].previousSibling !== 'undefined') {
                      imageContainer.childNodes[i].previousSibling.className = 'active';
                      imageContainer.childNodes[i].className = '';
                  }
              }
         }

</script>

Not tested it but that's the sort of thing you want to be doing 没有测试过,但这就是你想做的事情

I think you are mixing the src and the link by itself. 我认为您本身就是在混合src和链接。

If you want to create everything on the client side you can keep an array with the information of both field per image: 如果要在客户端创建所有内容,则可以保留一个数组,其中包含每个图像的两个字段的信息:

var img = [ {link='xxx', src="obrazky/0.png"}, {link='yyy' src="obrazky/1.png"},... ]

Then in your template, you have to wrap the image with a link: 然后,在模板中,您必须使用链接包装图像:

<a id='imgDemoLink'> <img id='imgDemo'></a>

and then in your script you should update both DOM elements: 然后在脚本中更新两个DOM元素:

imgElement.src = img[i.src];

Then get the DOM related link: 然后获取与DOM相关的链接:

var aElement = document.getElementById("imgDemoLink");
aElement.href = img[i.link]

Let me know if you need any extra help there... 让我知道您是否需要任何其他帮助...

Simply add the url corresponding to each image to an array, and add click events to the images. 只需将与每个图像相对应的url添加到数组,然后将click事件添加到图像。 The click event should redirect the user to the url corresponding to the clicked image. click事件应将用户重定向到与单击的图像相对应的url。

<script>
var img = new Array("obrazky/0.png", "obrazky/1.png", "obrazky/2.png", "obrazky/3.png");
//add this array for urls
var urls = new Array("example1.com", "example2.com", "example3.com", "example4.com");

var imgElement = document.getElementById("imgDemo");
var i = 0;
var imgLen = img.length;

function nxt()
{
    if(i < imgLen-1)
        {
            i++;
        }
    else{
            i=0;                
        }

        imgElement.src = img[i];
        //add click event to redirect 
     document.getElementById("imgDemo").addEventListener("click", function(){
         window.location.href = urls[i];
     });                      
}

function prvs()
{
    if(i > 0)
        {
            i--;
        }
    else
    {
        i = imgLen-1;
    }
        imgElement.src = img[i];
     //add click event to redirect 
     document.getElementById("imgDemo").addEventListener("click", function(){
         window.location.href = urls[i];
     });                   
}
</script>

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

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