简体   繁体   中英

How to execute a function on the right elements?

I am templating a HUGO website with a list page with cards. I have audio files from content in each card. Here are the html elements :

<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 :

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.

I have a for loop for the event listener on the buttons :

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.

I guess I need to querySelectorAll audio files and iterate on it ? How to execute the toggleAudio() function on the right audio files ?

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();
    }
  })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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