簡體   English   中英

我一直收到“未捕獲的ReferenceError:未定義imgArray”錯誤

[英]I keep getting an “Uncaught ReferenceError: imgArray is not defined” error

我已經寫了一些代碼作為淡入和淡出一些圖像的對象,只有當我要求構建幻燈片時,我才得到一個

“未捕獲的ReferenceError:未定義imgArray”。

任何人都可以幫助我為什么會收到此錯誤。 謝謝。

const slideShow = {
  curIndex: 0,
  imgDuration: 10000,
  slider: document.querySelector('.banner__slider').childNodes,

  imgArray: [
    'images/background/img3.jpg',
    'images/background/img1.jpg',
    'images/background/img2.jpg'
  ],

  buildSlideShow(arr) {
    for (i = 0; i < arr.length; i++) {
      const img = document.createElement('img');
      img.src = arr[i];
      slider.appendChild(img);
    }
  },

  slideShow() {

    function fadeIn(e) {
      e.className = "fadeIn";
    };

    function fadeOut(e) {
      e.className = "";
    };

    fadeOut(slider[curIndex]);
    curIndex++;
    if (curIndex === slider.length) {
      curIndex = 0;
    }

    fadeIn(slider[curIndex]);

    setTimeout(function () {
      slideShow();
    }, imgDuration);
  },
}; 

slideShow.buildSlideShow(imgArray).slideShow();

您收到錯誤,因為代碼中沒有imgArray變量。 您可以將其更改為:

slideShow.buildSlideShow(slideShow.imgArray).slideShow();

這解決了一個問題,但創建了另一個問題。 buildSlideShow方法不返回任何內容。 因此, .slideShow()方法將再次拋出錯誤。 由於imgArrayslideShow對象的屬性,因此您可以使用this關鍵字。 將方法更改為:

buildSlideShow() {

  for (i = 0; i < this.imgArray.length; i++) {
    const img = document.createElement('img');
    img.src = this.imgArray[i];
    slider.appendChild(img);
  }

  return this;
}

buildSlideShow ,使用return this對象的實例。 這樣你可以鏈接方法。

 const slideShow = { curIndex: 0, imgDuration: 10000, // slider: document.querySelector('.banner__slider').childNodes, imgArray: [ 'images/background/img3.jpg', 'images/background/img1.jpg', 'images/background/img2.jpg' ], buildSlideShow() { console.log("inside buildSlideShow method"); for (i = 0; i < this.imgArray.length; i++) { console.log(this.imgArray[i]); const img = document.createElement('img'); img.src = this.imgArray[i]; //slider.appendChild(img); } return this; }, slideShow() { console.log("inside slideShow method") } } slideShow.buildSlideShow() .slideShow(); 

(我已經注釋掉slider代碼)

imgArray不是全局變量,它是Object slideShow屬性。 您應該將slideShow.imgArray傳遞給該函數

slideShow.buildSlideShow(slideShow.imgArray).slideShow();

並且還修復了uildSlideShow(arr){...}開頭缺少b的類型。 它應該是buildSlideShow(arr){...}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM