-3

我需要展示一些来自数组的图片(是的,它必须来自任务要求的数组)。该网页向我显示了图像的边框,但没有显示实际图像。作为 JS 的新用户,我在某些事情上失败了,但我知道在哪里。这是我的代码..

function showImg() {
  var imagenes = ["/img/sony.jpg", "/img/coke.jpg"];
  document.getElementById("showImg_1"). = imagenes;
}
<div class="hero_2">
  <div class="subClient">
    <h2 class="subClient_1">"Conoce alguno de nuestros clientes..."</h2>
    <a class="boton" href="#conocelos" onclick="showImg()">Conocelos</a>
  </div>
</div>

<div id="conocelos">
  <img id="showImg_1" height="350px" width="200px">

</div>

4

5 回答 5

0

你需要这样的脚本,基本上“images[0]”使用键来访问值

  parent = document.getElementById('conocelos')
  images.forEach(function(path_image,index){
  if(index = 0 ){
    existent_image = document.getElementById('showImg_1');
    existent_image.src = path_image;
  }else{
    newImg = document.createElement('img');
    newImg.src = path_image;
   parent.appendChild(newImg);
  }
 }
于 2021-05-10T16:34:36.947 回答
0

如果您在没有服务器的情况下使用 vanilla JS,则无法从您的计算机或 api 上的文件中获取数据,但如果您有服务器,请尝试获取功能

如果您使用 node.js,请使用 fs 包

或者您可以更改图像标签的 src:

document.getElementById("showImg_1").src = imagenes[*index*]

于 2021-05-10T16:20:18.197 回答
0

如果要动态更改 html 中 img 标签的 src,则需要更改 DOM elem 的 src 属性。

function showImg() {
    var imagenes = ["/img/sony.jpg"];
    document.getElementById("showImg_1").src = imagenes[0];
};

这将从该数组的第一个索引中获取 src。

如果要遍历数组,则需要使用循环。

您发布的代码的问题是您的意图不是很清楚。您是否正在尝试创建图像轮播?

于 2021-05-10T16:21:46.847 回答
0
  1. 线
    document.getElementById("showImg_1"). = imagenes;

在“。”之后缺少一些东西

您需要进行更改<img,使 src 指向 url:https ://www.w3schools.com/tags/tag_img.asp

  1. imagenes 是一个数组,所以你不能像这样分配它。要使用它的第一个元素,你必须这样做imagenes[0]
于 2021-05-10T16:20:06.973 回答
0
  • 你在这里缺少 asrc和 a[someIndex]document.getElementById("showImg_1"). = imagenes;

  • 您还需要 preventDefault 来停止链接以卸载页面

尝试这个

const imagenes = ["https://banner2.cleanpng.com/20180715/tk/kisspng-sony-xperia-xz-premium-sony-xperia-z3-logo-sony-ericsson-5b4b5a50bc7934.963331681531664976772.jpg", "https://logoeps.com/wp-content/uploads/2011/05/coke-logo.jpg"];

document.querySelector(".subClient").addEventListener("click", function(e) {
  const tgt = e.target;
  if (tgt.classList.contains("boton")) {
    e.preventDefault();
    document.getElementById("showImg_1").src = imagenes[tgt.dataset.idx];
  }
});
<div class="hero_2">
  <div class="subClient">
    <h2 class="subClient_1">"Conoce alguno de nuestros clientes..."</h2>
    <a class="boton" href="#conocelos" data-idx="0">Sony</a> <a class="boton" href="#conocelos" data-idx="1">Coke</a>
  </div>
</div>

<div id="conocelos">
  <img id="showImg_1" height="350px" width="200px">

</div>

于 2021-05-10T16:23:39.413 回答