如何更改位于另一个元素的 innerhtml 中的图像源?

how to change the source of an image, which is in the innerhtml of another element?

我的 innerhtml 中有一个带有图像的按钮,我想更改此图像

<button id="button1"><img src="someimage.png"></button>

我试过这样的事情(在一个函数中,由按钮调用):

this.innerhtml.setAttribute("src","someotherimage.png");
this.innerhtml="<img src="someotherimage.png">";

我有多个触发相同功能的按钮,但我希​​望该功能仅更改触发该功能的按钮的 img。 我可以在不给图像 ID 并使用大量 if 语句将图像 ID 与按钮匹配的情况下执行此操作吗?

提前致谢

使用 event 参数,获取 currentTarget(侦听器附加到的元素 - 这将是按钮),然后您可以从那里获得 child <img>.children[0].

.addEventListener('click', (e) => {
  e.currentTarget.children[0].src = 'someotherimage.png';
});

更具体到 img 标签

.addEventListener('click', ($event) => {
    event.target.querySelector('img').src="someotherimage.png";
 });