Uncaught TypeError: Cannot set properties of undefined (setting ‘backgroundColor‘)的解决方法

前言

首先看代码:

        let colors = ['green', 'yellow', 'black', 'blue', 'pink', 'yellowgreen']
        let random = Math.floor(Math.random() * colors.length)

        const div = document.querySelectorAll('div')
        div.style.backgroundColor = colors[random]

这个代码很简单,其实就是通过随机数来改变div的颜色,达到每次刷新颜色都是随机的目的。

但是,这个只是学习的而已,为了加强对内置对象Math的方法使用而做的。

那么还没有学到API的小聪明就会,好奇,为什么这个代码会在浏览器报错,并出现下面的问题?


分析

其实解决方法还是蛮简单的,首先我们得了解document.querySelectorAll方法的意义,我们可以在浏览器输入MDN,打开第一个连接,如下图:

这个时候,我们把document.querySelectorAll方法输入到搜索框,进行查找:

然后我们查看返回值:

可以发现,document.querySelectorAll返回的是一个list,但是我们的代码中最后一句,右边是一个值,这里就出现了错误。

所以这个时候,我们就得考虑把document.querySelectorAll更改为document.querySelector。我们先去MDN查看document.querySelector的返回值:

非常符合一对一原则,所以我们删去All,运行正确:

最后

最后代码:

        let colors = ['green', 'yellow', 'black', 'blue', 'pink', 'yellowgreen']
        let random = Math.floor(Math.random() * colors.length)

        // 注意不要写出document.querySelectorAll,这样会报错!!
        const div = document.querySelector('div')
        div.style.backgroundColor = colors[random]

猜你喜欢

转载自blog.csdn.net/m0_54066656/article/details/129572086
今日推荐