在控制台中工作,但在编辑器中不起作用



我正在用一个程序练习JavaScript,该程序应该根据随机数改变骰子的图像。如果我把这一行放到控制台图像就会改变;它的工作原理。

document.querySelector("img.img1").setAttribute("src", "images/dice1.png");

但是如果我把它放在编辑器中,我得到以下错误消息:

index.js:5 Uncaught TypeError: Cannot read properties of null (reading 'setAttribute')在index.js: 5

为什么?

我忘记在头部添加js链接文件的链接了。我把这行

<script src="index.js" charset="utf-8"></script>

只能出现在HTML文件的头部。我应该把它区别开来,或者把它放在正文部分的末尾。

最新更新