无法使用img.src更改src属性



我在使用.src属性时遇到问题,我打算使用它来使用随机生成的数字更改每次加载html页面时的图像。出于某种原因,img.src不会更改目标id的src属性并停止我的循环"对于";出于某些原因。。。(代码在一个单独的HTML文件中运行(以下是js代码:

const images_for_you = [
'./assets/Series/Aggretsuko.jpg',
'./assets/Series/AngelBeast.jpg',
'./assets/Series/Arcane.jpg',
'./assets/Series/BreakingBad.jpg',
'./assets/Series/BlackMirror.jpg',
'./assets/Series/BluePeriod.jpg',
'./assets/Series/Django.png',
'./assets/Series/GreatPretender.jpg',
'./assets/Series/Hilda.jpg',
'./assets/Series/JeVeuxMangerTonPancreas.jpg',
'./assets/Series/LaLigneVerte.jpg',
'./assets/Series/LeCupheadShow.jpg',
'./assets/Series/LesEnfantsDeLaBalaine.jpg',
'./assets/Series/LeVoyageTeChihiro.jpg',
'./assets/Series/QuoiQuilArriveJeVousAime.jpg',
'./assets/Series/NosMotsCommeDesBulles.jpg',
'./assets/Series/SkyHighSurvival.jpg',
'./assets/Series/toradora.jpg',
'./assets/Series/SkyHighSurvival.jpg',
'./assets/Series/Viking.jpg']; // 20
const images_japanese_animation = [];
const images_netflix_originals = [];
const images_films_sf = [];
const images_studios_ghibli = [];
const images_dessins_animes = [];
function random_array(iterations){
var randomArray = [];
for (let i = 0; i<iterations; i++){
randomArray.push(Math.floor(Math.random()*iterations))
}
return randomArray
}
function attribute_for_you(number_of_images){
let randArr = random_array(number_of_images)
let index_for_you = [
'for_you_1',
'for_you_2',
'for_you_3',
'for_you_4',
'for_you_5',
'for_you_6',
'for_you_7',
'for_you_8',
'for_you_9',
'for_you_10',
'for_you_11',
'for_you_12',
'for_you_13',
'for_you_14'
]

for (let i = 0; i < number_of_images; i++){
console.log(images_for_you[randArr[i]])
console.log(randArr[i])
console.log(i)
var img_index = document.getElementsById(index_for_you[i])
img_index.src = images_for_you[randArr[i]]
} 
}
attribute_for_you(10)

谢谢你的帮助此外,ID是正确的,我检查了多次:(

更新

如果HTML 中没有这些图像元素,您还需要将它们添加到HTML主体中

for (let i = 0; i < number_of_images; i++){
console.log(images_for_you[randArr[i]])
console.log(randArr[i])
console.log(i)
var img_index = document.getElementById(index_for_you[i])
//if cannot find that image element, we need to add it
if(!img_index) {
imageElement = document.createElement('img');
imageElement.setAttribute("id", index_for_you[i]);
//add the image element to the body
document.body.appendChild(imageElement);
}
img_index = document.getElementById(index_for_you[i])
img_index.src = images_for_you[randArr[i]]
} 

旧答案

这里有语法错误

var img_index = document.getElementsById(index_for_you[i])

它应该是getElementById,而不是getElementsById(Elements不应该有s(

更改应为

var img_index = document.getElementById(index_for_you[i])

var img_index=document.getElementsById(index_for_you[i](

getElementById用于获取具有特定id的html元素,但您正在使用它来获取JS变量,这不是它的工作方式,因此它会显示错误。

最新更新