其他HTML页面上的TypeError函数为null

时间:2019-04-26 15:10:55

标签: javascript function error-handling null

我有一个大问题。我为全屏图像滑块编写了一个函数。该功能在我的index.html页面上运行良好,但是在其他HTML页面上,我在控制台中收到此错误:

  

TypeError:arrowLeft为空http://127.0.0.1:5501/Core/app.js:24

在Mozilla Firefox和

  

未捕获的TypeError:无法读取null的属性'addEventListener'       在app.js:24

在Google Chrome enter image description here

并且此错误还会导致其他问题。

有人知道为什么会这样吗?

HTML:

 <!-- !Showcase -->
  <div id="showcase">
    <div id="arrow-left" class="arrow"></div>
    <div id="slider">
      <div class="slide slide1"></div>
      <div class="slide slide2 "></div>
      <div class="slide  slide3"></div>
    </div>
    <div id="arrow-right" class="arrow"></div>
  </div>

!!!!! CSS !!!!!!!!!!

// Showcase!
#showcase,
#slider,
.slide-content {
    height: 100vh;
    width: 100%;
    overflow-x: hidden;
}

#showcase {
    position: relative;
    height: 100vh;
    width: 100%;
}

.slide {
    width: 100%;
    height: 100%;
}

.slide1 {
    background: url(/Core/img/lazar1.jpg) no-repeat center center/cover;
}

.slide2 {
    background: url(/Core/img/lazar2.jpg) no-repeat center center/cover;
}

.slide3 {
    background: url(/Core/img/lazar3.jpg) no-repeat center center/cover;
}

.arrow {
    cursor: pointer;
    position: absolute;
    top: 50%;
    margin-top: -50px;
    border-style: solid;
}


#arrow-left {
    border-width: 30px 40px 30px 0;
    border-color: transparent blue transparent transparent;
    left: 0;
    margin-left: 30px;
}

#arrow-right {
    border-width: 30px 0 30px 40px;
    border-color: transparent blue transparent blue;
    right: 0;
    margin-right: 30px;
}

!!!!!!! JAVASCRIPT !!!!!!!!!!!
//FOR SLIDER    
let sliderImages = document.querySelectorAll(".slide"),
    arrowLeft = document.querySelector("#arrow-left"),
    arrowRight = document.querySelector("#arrow-right"),
    current = 0;

function reset() {
    for (let i = 0; i < sliderImages.length; i++) {
        sliderImages[i].style.display = 'none';
    }
}

function startSlide() {
    reset();
    sliderImages[0].style.display = 'block';
}

function slideLeft() {
    reset();
    sliderImages[current - 1].style.display = 'block';
    current--;
}

arrowLeft.addEventListener('click', function (e) {
    if (current === 0) {
        current = sliderImages.length;
    }
    slideLeft();
})


function slideRight() {
    reset();
    sliderImages[current + 1].style.display = 'block';
    current++;
}
arrowRight.addEventListener('click', function (e) {
    if (current === sliderImages.length - 1) {
        current = -1;
    }
    slideRight();
})

startSlide();

1 个答案:

答案 0 :(得分:0)

最后2小时后,我解决了这个问题。 我的函数在所有页面上运行,因此没有滑块的页面t have the html code and my function was looking for them that不能解释为什么第一页可以正常工作,而其他页面却让我“空”。 谢谢您的帮助。