首页 > 解决方案 > 如何将图像源存储在数组中?

问题描述

我正在努力做到这一点,以便当我单击图像时,另一张图像将显示在同一页面上,但截至目前,当我单击图像时,它只给我图片链接而不是给我图片。

<!DOCTYPE html>
<html>
<head>
<style>
</style>
</head>
<body>

<h2>JavaScript Arrays</h2>

<p>JavaScript array elements are accessed using numeric indexes (starting from 0).</p>

<p id="output"></p>
   
<img id="ima1" src="https://i.imgur.com/pe18NpF.jpg" style="width:150px">
<div id="image1"></div>
<script>
var images = [
    'https://i.imgur.com/xwZRPaT.jpg'
];

document.getElementById("ima1").addEventListener("click", showPic4);
function showPic4() {
document.getElementById("image1").innerHTML = images[0];
}

</script>

</body>
</html>

标签: javascriptarraysimageaddeventlistener

解决方案


The first issue with your JavaScript is in this line here:

document.getElementById("image1").innerHTML = images[0];

What you're doing here is that you are getting the HTML Element with the id "image1" and then setting its inner HTML to the value in images[0].

The reason you're getting the picture's link instead of the image is because the value inside images[0] is a string, not an image.

There are many ways to achieve your original goal. One way, keeping consistency with your current code is to target an img tag's src attribute. Consider the code block below:

<img id="img1" src="https://large-type.com/twitter-card.png?v2" style='width:150px'>
<img id="img2" style='width:150px'></img>
<script>
    var images = [
        'https://images.megapixl.com/5692/56920966.jpg'
    ];

    document.getElementById("img1").addEventListener("click", showPic);
    
    function showPic() {
        document.getElementById("img2").setAttribute('src', images[0]);
    }
</script>

The difference here is that the HTML element the showPic function is targetting is an img element instead of a div. Now we can just add an img src like you did for the first image using the setAttribute function.

Hope this helps!


推荐阅读