所以我在HTML中链接了文件夹中的两个图像:images/但在javascript中,我试图让骰子在每次刷新后随机更改这些图像。我不知道为什么不起作用
这是HTML代码
<div class="container">
<h1>Refresh Me</h1>
<div class="dice">
<p>Player 1</p>
<img class="img1" src="images/dice6.png">
</div>
<div class="dice">
<p>Player 2</p>
<img class="img2" src="images/dice6.png">
</div>
</div>
这是js代码
imgArray = [
"dice1.png",
"dice2.png",
"dice3.png",
"dice4.png",
"dice5.png",
"dice6.png"
]
function images(){
// the random images
var randomNumber1 = Math.floor(Math.random() * imgArray.length);
// get images at randomNumber1
selectedImages = imgArray[randomNumber1]
// display the images()
document.getElementByClassName("img1").src = "./images/${selectedImages}"
}
注意:我是一个新的学习者,仍在努力理解javascript。感谢你谦逊的答复和帮助。如果不是太多,使解释简单,这样我就可以跟随。
在修复上的代码之后
function images(){
// the random images
var randomNumber1 = Math.floor(Math.random() * imgArray.length);
// get images at randomNumber1
selectedImages = imgArray[randomNumber1]
// display the images()
document.getElementsByClassName("img1")[0].src = './images/${selectedImages}'
}
window.onload = images;
当我刷新页面时,我有问题,这就是它显示的内容
在此处输入图像描述
再次感谢您的帮助。
这是显示的内容
好的,修复了,我用改了
function images(){
// the random images
var randomNumber1 = Math.floor(Math.random() * imgArray.length);
// get images at randomNumber1
selectedImages = imgArray[randomNumber1]
// display the images()
document.getElementsByClassName("img1")[0].src = 'images/' + selectedImages;
document.getElementsByClassName("img2")[0].src = 'images/' + selectedImages;
}
window.onload = images;
这里有几个问题:
-
getElementbyClassName
不是一个有效的函数。它应该是getElementsByClassName
,它返回具有该类名的类似数组的元素集合。因此,通过写入getElementsByClassName[0]
来选择第一个值。 -
此处用单引号替换双引号:
'images/' + selectedImages
-
加载窗口时不要忘记调用函数。
最终代码:
function images(){
// the random images
var randomNumber1 = Math.floor(Math.random() * imgArray.length);
// get images at randomNumber1
selectedImages = imgArray[randomNumber1]
// display the images()
document.getElementsByClassName("img1")[0].src = 'images/' + selectedImages;
}
window.onload = images;