无法获取未定义或空引用的属性“ toggle”(来自IE9)

时间:2019-08-05 13:46:01

标签: javascript

我有一个轮播,它可以在Chrome,Mozilla和IE中使用边缘文档模式以及文档模式10正常工作。

我在本地运行该站点,并且当我切换到文档模式9时,我得到以下信息... SCRIPT5007:无法获取未定义或空引用的属性“ toggle”

我已经检查了其他相关问题,但似乎只有一个可能是问题,那就是在调用时可能未加载DOM。

因此,我尝试在控制台的控制台中在代码的不同位置记录有问题的元素。

const carousel__imgs = document.getElementsByClassName("carousel__imgs");
console.log(carousel__imgs[0]); -- Logs the desired element

let counter = 0;

// Starts the carousel
function carouselInitAndRun() {

  // Makes the first image visible
  carousel__imgs[0].classList.toggle("img-opacity");

  // Runs the carousel every 2,5 seconds
  setInterval(carouselRun, 2500);
}

// Keeps the carousel running
function carouselRun() {

  // Increase counter
  counter++;

  // If counter is greater than 0, show next image and hide previous one
  if (counter > 0 && counter < carousel__imgs.length) {

    // Changes the opacity of the current image to 1
    carousel__imgs[counter].classList.toggle("img-opacity");

    // Changes the opacity of the previous image to 0
    carousel__imgs[counter - 1].classList.toggle("img-opacity");

    // else if counter = 0, add image opacity to all
  } else if (counter === carousel__imgs.length) {

    // Loops through all images
    for (let i = 0; i < carousel__imgs.length; i++) {

      // Changes opacity of images to 0
      carousel__imgs[i].classList.add("img-opacity");

    }

    // Changes opacity of first image to 1
    carousel__imgs[0].classList.toggle("img-opacity");

    // Reset counter
    counter = 0;

  }
}

// window.addEventListener("load", () => {
//   console.log("Page Loaded");
//   console.log(carousel__imgs[0]);  -- Logs the desired element
//   carouselInitAndRun();
// });

carouselInitAndRun();

我希望从日志中得到的是HTML集合中的第一张图像,我愿意。无论是在将集合设置为变量之后,还是在错误发生之前,我都调用它。我总是从日志中获取期望的元素。但是,一旦到了该元素将一个类切换到它的时候,我就会收到错误消息。

我还尝试将函数放入setTimeout中,以为如果将其从调用堆栈中取出并放入队列中,也许可以解决问题。

然后我尝试了window.addEventListener('load',carouselInitAndRun);

仍然是相同的错误。

谢谢。

0 个答案:

没有答案