3

这是我的第一个 JavaScript。它花了很多时间,但无法让它工作。

显然,它应该做的是在打开“详细信息/摘要”部分时更改图片。仅供参考,这是我试图解决的这个问题的后续行动。有人看到我做错了什么吗?

<body>
  <script type="text/javascript">
    function changeImage(a) {
      document.getElementById("img").src = a;
    }
    details.addEventListener("toggle", event => {
      if (details.open) {
        changeImage("https://via.placeholder.com/50/ff0000");
      } else {
        changeImage("https://via.placeholder.com/50/0000ff");
      }
    });
  </script>

  <details>
    <summary>
      <table>
        <td width="64">#910</td>
      </table>
    </summary>
    <table>
      <td width="64">#910</td>
    </table>
  </details>

  <img id="img" src='https://via.placeholder.com/50'>
</body>

4

2 回答 2

1

那是你缺少的部分:const details = document.querySelector('details'). 然后它会工作。

    function changeImage(a) {
      document.getElementById("img").src = a;
    }
const details = document.querySelector('details')
    details.addEventListener("toggle", event => {
      if (details.open) {
        changeImage("https://via.placeholder.com/50/ff0000");
      } else {
        changeImage("https://via.placeholder.com/50/0000ff");
      }
    });
<body>
  <script type="text/javascript">

  </script>

  <details>
    <summary>
      <table>
        <td width="64">#910</td>
      </table>
    </summary>
    <table>
      <td width="64">#910</td>
    </table>
  </details>

  <img id="img" src='https://via.placeholder.com/50'>
</body>

于 2022-01-19T19:43:16.817 回答
1

使用event.currentTarget;,它指向正在监听事件的标签。那个事件是一个简单的“点击”,从来没有读过“切换”是一个事件,我今天学到了一些东西。

const changeImage = event => {
  const clicked = event.currentTarget;
  const img = document.querySelector('.img');

  if (clicked.matches('details')) {
    if (clicked.open) {
      img.src = "https://via.placeholder.com/50/ff0000";
    } else {
      img.src = "https://via.placeholder.com/50/0000ff";
    }
  }
}

document.querySelector('details').addEventListener('click', changeImage)
<details>
  <summary>
    <table>
      <td width="64">#910</td>
    </table>
  </summary>
  <table>
    <td width="64">#910</td>
  </table>
</details>
<img class="img" src='https://via.placeholder.com/50'>

于 2022-01-19T19:58:40.177 回答