首页 > 解决方案 > 如果页面上不存在目标元素,javascript会忽略代码

问题描述

Soo,我是一个完整的 javascript 初学者,我有这个轮播代码(来自本教程:https ://www.youtube.com/watch?v=gor5BvT2z88 ),它只存在于其中一个页面上. 我需要在代码中添加什么,以便当我在不包含此轮播的其他页面上时不会收到此错误:Uncaught TypeError: Cannot read properties of null (reading 'addEventListener')

let slidePosition = 0;
const slides = document.getElementsByClassName('carousel__item');
const totalSlides = slides.length;

document.
getElementById('carousel__button--next')
    .addEventListener("click", function () {
        moveToNextSlide();
    });
document.
getElementById('carousel__button--prev')
    .addEventListener("click", function () {
        moveToPrevSlide();
    });

function updateSlidePosition() {
    for (let slide of slides) {
        slide.classList.remove('carousel__item--visible');
        slide.classList.add('carousel__item--hidden');
    }

    slides[slidePosition].classList.add('carousel__item--visible');
}

function moveToNextSlide() {
    if (slidePosition === totalSlides - 1) {
        slidePosition = 0;
    } else {
        slidePosition++;
    }

    updateSlidePosition();
}

function moveToPrevSlide() {
    if (slidePosition === 0) {
        slidePosition = totalSlides - 1;
    } else {
        slidePosition--;
    }

    updateSlidePosition();
}
<section id="carousel-section">
      <div class="carousel">
        <h2 class="carousel-header">FEATURED WORK</h2>
        <div class="carousel__item carousel__item--visible"><img
            src="./carousel pictures/slide show pictures/slide1.jpg" alt=""></div>
        <div class="carousel__item"><img src="./carousel pictures/slide show pictures/slide2.JPG" alt=""></div>
        <div class="carousel__item"><img src="./carousel pictures/slide show pictures/slide3.JPEG" alt=""></div>
        <div class="carousel__item"><img src="./carousel pictures/slide show pictures/slide4.JPG" alt=""></div>
        <div class="carousel__item"><img src="./carousel pictures/slide show pictures/slide5.JPG" alt=""></div>
        <div class="carousel__actions">
          <button id="carousel__button--prev" aria-label="previous slide">
            < </button> <button id="carousel__button--next" aria-label="next slide"> >
          </button>
        </div>
    </section>

标签: javascriptcarousel

解决方案


The error in question is being thrown as a result of this code looking for carousel-related DOM elements on pages where the functionality isn’t in use. While the current answers do assist in the resolution of the issue, I feel there is a better way to resolution that can also be of use in many other scenarios where page-specific functionality can be included/excluded as necessary:

As discussed in the comments on the original question, the clean way to resolve this is to move all carousel-related code to a separate .js file, and reference that new file only on pages where you explicitly need this carousel functionality.

This way, you’ll be segmenting your JavaScript code more neatly, reduce unnecessary networking, memory, and processing overhead, and avoid script errors on pages that don’t leverage this functionality.


推荐阅读