简体   繁体   English

如何在正确的元素上执行功能?

[英]How to execute a function on the right elements?

I am templating a HUGO website with a list page with cards.我正在模板一个带有卡片列表页面的 HUGO 网站。 I have audio files from content in each card.我有来自每张卡内容的音频文件。 Here are the html elements :这是html元素:

<audio class="podcast__audio" src="{{ $podcast.RelPermalink }}"></audio>

I have a button for each card to play audio :每张卡都有一个按钮来播放音频:

<button class="podcast__player_button">
    <img class="podcast__player_play" src="/images/podcast/play.png">
</button>

In Javascript I play audio with this function :在 Javascript 中,我使用此功能播放音频:

const podcastAudio = document.querySelector('.podcast__audio');

function toggleAudio () {
  if (podcastAudio.paused) {
    podcastAudio.play();

  } else {
    podcastAudio.pause();
  }
}

I display 4 cards on the list page and each card has one different audio file to play.我在列表页面上显示了 4 张卡片,每张卡片都有一个不同的音频文件可以播放。

I have a for loop for the event listener on the buttons :我在按钮上有一个用于事件侦听器的 for 循环:

const podcastPlayerButton = document.querySelectorAll('.podcast__player_button');

for (let i = 0; i < podcastPlayerButton.length; i++) {
  podcastPlayerButton[i].addEventListener('click', toggleAudio);
}

It works fine but it toggles only the first audio file of the page (which makes sense) but I want it to play the audio file linked to each card.它工作正常,但它只切换页面的第一个音频文件(这是有道理的),但我希望它播放链接到每张卡的音频文件。 The first podcast__player_button button should play the first podcast__audio file, the second button should play the second audio file and so on.第一个podcast__player_button按钮应该播放第一个podcast__audio文件,第二个按钮应该播放第二个音频文件,依此类推。

I guess I need to querySelectorAll audio files and iterate on it ?我想我需要查询querySelectorAll音频文件并对其进行迭代? How to execute the toggleAudio() function on the right audio files ?如何在正确的音频文件上执行toggleAudio()函数?

Ok because buttons and audio files have the same index this code works :好的,因为按钮和音频文件具有相同的索引,此代码有效:

for (let i = 0; i < podcastPlayerButton.length; i++) {
  podcastPlayerButton[i].addEventListener('click', function () {
    if (podcastAudio[i].paused) {
      podcastAudio[i].play();
    } else {
      podcastAudio[i].pause();
    }
  })
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM