javascript - 如何将图像源存储在数组中?
问题描述
我正在努力做到这一点,以便当我单击图像时,另一张图像将显示在同一页面上,但截至目前,当我单击图像时,它只给我图片链接而不是给我图片。
<!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>
解决方案
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!
推荐阅读
- rest - 如何跟踪 approot 下特定 OneDrive 文件夹的更改?
- jquery - 自己的搜索功能后jquery自动完成更新结果
- regex - 正则表达式匹配十六进制
- excel - 在列中查找下一个红色单元格,返回该单元格的行号
- php - PHP 8:将“资源”分配为属性、参数或返回类型
- tcl - 带有 TCL 控制台的 Vivado 触发功能
- iframe - 如何通过PHP中的javascript在iframe的标题中添加链接
- unzip - 提取子文件夹但不提取父文件夹
- spring-boot - com.sun.xml.internal.ws.spi.db.DatabindingException:未知的 JAXBContext 实现
- javascript - 如何仅针对特定帖子类型将自定义字段数据添加到 Yoast 插件页面分析