用于更改图像源的 JavaScript 按钮不起作用

问题描述 投票:0回答:1

我有一组按钮,每个按钮都需要将图像更改为不同的源,并显示选择了哪个按钮(保留 onclick 外观)。

我希望它从列表中获取元素的名称,并根据该项目的变量执行操作,但主要设置源和标题。 脚本:

    const picList= {
      { "nature": { src: "nature.png", title: "" } }
      { "face":   { src: "face.png", title: "" } }
    };

    function changePic(picName) 
    {
      document.getElementById('currentPic').src = picList[picName].src;
      document.getElementById('currentPic').title = picList[picName].title;
    }

身体:

<img id="currentPic" src="nature.png">
          <button onclick="changePic('face')" type="button">Face</button> 
          <button onclick="changePic('nature')" type="button">Nature</button> 

很多建议让我创建一个常量来保存列表项数据,但这不起作用,正确设置每个元素应该是相同的?

现在我只看到它开头的图像,nature.png 和 onclick 似乎没有做任何事情。我看到一些帖子说它需要返回 false,但这也不起作用。

另外,如果我希望按钮保留 onclick 较深的颜色,直到单击另一个按钮,那么当单击另一个按钮时,哪里是重置它的好地方?

javascript html
1个回答
0
投票

使用内联事件处理程序通常不是一个好主意。

这是一个供您使用的想法。该代码片段使用

事件委托进行点击处理和 data-attributes 用于识别图像 id 和图像 src。

document.addEventListener(`click`, handle); // note: your object literal contained errors // (no comma between properties, too many/ // unnecessary curly braces) const picList = { nature: { src: "https://picsum.photos/id/29/200/100", title: "it's nature" }, face: { src: "https://picsum.photos/id/64/200/100", title: "an image of a face" }, original: { src: "https://picsum.photos/id/16/200/100", title: "the original picture" } }; function handle(evt) { const imgChangeFromButton = evt.target.dataset.imgChange; if (imgChangeFromButton) { const img = document.querySelector(evt.target.dataset.imgId); img.setAttribute(`src`, picList[imgChangeFromButton].src); return img.setAttribute(`title`, picList[imgChangeFromButton].title); } }
<img id="currentPic" src="https://picsum.photos/id/16/200/100">
<p>
  <!-- note: you don't need type="button" -->
  <button 
    data-img-change="face" data-img-id="#currentPic">Face</button>
  <button 
    data-img-change="nature" data-img-id="#currentPic">Nature</button>
  <button 
    data-img-change="original" data-img-id="#currentPic">Original</button>  
</p>

© www.soinside.com 2019 - 2024. All rights reserved.