首页 > 解决方案 > 我的脚本 js 不会改变我的照片 src

问题描述

我想动态添加图像并使用图像滑块。我写了一些脚本,在控制台中我看到更改 src,但在 HTML 中仍然是一张图片。这是一个代码:

HTML:

<div class="sliderItau">
   <a class="prevButton"> <img alt="prevButton" src="/images/prev.png"></a>
   <div class="jcarousel">
     <img id="image" src="/images/debito/itau_tela_02.png" alt=""></div>
   <a class="nextButton"><img alt="nextButton" src="/images/next.png"></a>
</div>

JS:

const images = []

let slideIndex = 1

function preload_images() {

    var image = new Image()
    image.src = 'images/debito/itau_tela_01.png'
    images[0] = image
    image = new Image()
    image.src = 'images/debito/itau_tela_02.png'
    images[1] = image
    image = new Image()
    image.src = 'images/debito/itau_tela_03.png'
    images[2] = image

}

preload_images()

const showSlidesItau = function (n) {
    let img = document.getElementById('image')
    let slides = img.src
    slides = images[slideIndex].src
    console.log(slides)
    console.log(images[slideIndex].src)
    if (n > slides.length) {
        slideIndex = 1
    }
    if (n < 1) {
        slideIndex = slides.length
    }
}

const plusSlides = function (n) {
    console.log(slideIndex)
    showSlidesItau((slideIndex += n))
}

const next = document.querySelector('.nextButton')
const prev = document.querySelector('.prevButton')
//buttons ITAU
next.addEventListener('click', function () {
    plusSlides(+1)
})
prev.addEventListener('click', function () {
    plusSlides(-1)
})

所以每次我按下 prev 或 next 按钮时,我在 colse 中的 src 都会发生变化。但不是在 HTML 中。知道为什么吗?

标签: javascripthtml

解决方案


我不是 JS-Pro,但我想指出一些事情。正如 GuyIncognito 已经在评论中写的那样,您必须直接设置 src 属性,而不是在复制的变量上。但是您的功能还有一些缺陷showSlidesItau()

在设置图像源之前进行检查 - 而不是之后

如果norslideIndex超出图像数组的索引范围,您仍会尝试设置它并收到错误。

将您的 slideIndex 设置为 n

否则图像会改变的唯一时间是当你在你的图像数组的开头或结尾时......

数组索引从 0 开始,以 array.length -1 结束

因此,如果您尝试类似 array[array.length] 的方法,您将收到错误消息。

我试着稍微改写一下这个函数:

const showSlidesItau = function (n) {
  let img = document.getElementById("image");
  // First check the index
  if (n >= images.length) {
    slideIndex = 0;
  } else if (n < 0) {
    slideIndex = images.length - 1;
  } else {
    slideIndex = n;
  }
  // then set the src attribute
  img.src = images[slideIndex].src;
  console.log(images[slideIndex].src);
};

我希望我能帮助你一点。


推荐阅读