Javascript 试图为html创建一个js类(每隔几秒钟更改一次背景图像),需要帮助吗

Javascript 试图为html创建一个js类(每隔几秒钟更改一次背景图像),需要帮助吗,javascript,html,class,Javascript,Html,Class,您好,我正试图使一个类在一个站点上有许多对象更改背景图像,而无需逐个创建每个对象 所以我这样做是为了改变一个“对象”的背景图像: 这很有效,所以我想让它成为一门课: class changingImageObject { constructor(img1, img2, img3, id) { this.image = [img1, img2, img3]; this.id = id; this.x = 0; }; disp

您好,我正试图使一个类在一个站点上有许多对象更改背景图像,而无需逐个创建每个对象

所以我这样做是为了改变一个“对象”的背景图像:

这很有效,所以我想让它成为一门课:

class changingImageObject {
    constructor(img1, img2, img3, id) {
        this.image = [img1, img2, img3];
        this.id = id;
        this.x = 0;
    };

    displayNextImage() { //Change the showed image x+1
        this.x = (this.x === 2) ? 0 : this.x + 1;
        document.getElementById(this.id).setAttribute("style", "background-image: url(" + this.image[this.x] + ")");
    };

    startTimer() { //Change image after 3sec (looping)
        setInterval(this.displayNextImage, 3000);
    };
}

const changingImages = new changingImageObject("assets/img1.jpeg", "assets/img2.jpeg", "assets/img3.jpeg", "myID");
changingImages.startTimer();
我在html的末尾添加了脚本,它创建了对象,但是displayNextImage函数给出了一个错误:UncaughtTypeError:无法读取null的属性“setAttribute” 下一次


感谢穆巴拉克,我似乎需要将我的方法绑定到构造函数

带更正的代码

constructor(img1, img2, img3, id) {
        this.image = [img1, img2, img3];
        this.id = id;
        this.x = 0;
        this.displayNextImage = this.displayNextImage.bind(this);
    };

现在我需要学习bind:)的用法。

多亏了穆巴拉克,我似乎需要将我的方法绑定到构造函数

带更正的代码

constructor(img1, img2, img3, id) {
        this.image = [img1, img2, img3];
        this.id = id;
        this.x = 0;
        this.displayNextImage = this.displayNextImage.bind(this);
    };

现在我需要学习bind:)的用法。

当你使用console.log
document.getElementById(this.id)
时,你会得到什么?哦,它是空的,当我在displayNextImage中使用console.log(this.id)时,它是未定义的,我不明白为什么。。。当我在构造函数中执行console.log(this.id)时,我得到了id…在setInterval之后,我的对象中的所有变量都变得未定义…我明白了。看来你需要。尝试将
this.displayNextImage.bind(this)
添加到您的构造函数中。当您使用console.log
document.getElementById(this.id)
时,会得到什么?哦,它为空,当我在displayNextImage中使用console.log(this.id)时,它是未定义的,我不明白为什么。。。当我在构造函数中执行console.log(this.id)时,我得到了id…在setInterval之后,我的对象中的所有变量都变得未定义…我明白了。看来你需要。尝试将
this.displayNextImage.bind(this)
添加到构造函数中。