【问题标题】:how to change the source of an image, which is in the innerhtml of another element?如何更改图像的来源,在另一个元素的innerhtml中?
【发布时间】:2021-10-12 15:34:04
【问题描述】:

我有一个按钮,其 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 与按钮匹配的情况下执行此操作吗?

提前致谢

【问题讨论】:

  • .innerHTML 只返回一个字符串。并且字符串没有 DOM 元素具有的方法。您可以选择图像作为按钮的子元素,并使用表达式document.querySelector("button img").src="newURL.png" 为其src 属性分配一个新值

标签: javascript html image innerhtml


【解决方案1】:

使用event 参数,获取currentTarget(监听器附加到的元素 - 这将是按钮),然后您可以从那里获取子&lt;img&gt;.children[0]

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

【讨论】:

    【解决方案2】:

    更具体的 img 标签

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多