gpt4 book ai didi

javascript - 更改子元素的 src

转载 作者:行者123 更新时间:2023-12-02 21:21:28 25 4
gpt4 key购买 nike

我有三个按钮,每个按钮都有一张带有空 src 的图像。我试图在单击每个按钮时随机更改图像 src ,如果我正确地看到这一点,控制台会告诉我,当我单击时,图像正在生成,但我似乎无法它显示在浏览器上,我真的不明白为什么。

const images = 
["https://i.picsum.photos/id/102/60/60.jpg","https://i.picsum.photos/id/1024/60/60.jpg",
"https://i.picsum.photos/id/1062/60/60.jpg","https://i.picsum.photos/id/1069/60/60.jpg"];

const buttons = document.querySelectorAll("button");

buttons.forEach(function(el){ el.addEventListener("click", card); })

function card(){
let random = Math.floor( Math.random() * 9);
let image = this.children;
console.log(image);
image.src = images[random];
console.log(image.src); }
  <div>
<button type="button"><img src="" alt=""></button>
<button type="button"><img src="" alt=""></button>
<button type="button"><img src="" alt=""></button>
</div>

最佳答案

let image = this.children

this.children 指的是 dom 元素的集合,而不是单个元素;因此您需要指定您案例中的第一个。

如果除了图像之外还有多个子节点,您不妨考虑使用querySelector('img')

const images = 
["https://i.picsum.photos/id/102/60/60.jpg",
"https://i.picsum.photos/id/1024/60/60.jpg",
"https://i.picsum.photos/id/1062/60/60.jpg",
"https://i.picsum.photos/id/1069/60/60.jpg"];

const buttons = document.querySelectorAll("button");

buttons.forEach(el => el.addEventListener("click", card))

function card() {
const randomImageUrl = images[Math.floor(Math.random() * images.length)];
const image = this.children[0];
image.src = randomImageUrl;
console.log(image.src);
}
<div>
<button type="button"><img src="" alt=""></button>
<button type="button"><img src="" alt=""></button>
<button type="button"><img src="" alt=""></button>
</div>

关于javascript - 更改子元素的 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60835082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com