简体   繁体   中英

Iterate through multiple elements of querySelectorAll with forEach

Problem is as following: I have created a separate JS file, in which I want to iterate through elements belonging to a certain class audioz . In the second line of my JS code I use the addEventListener on item , however the code does not seem to work with item , only if I put document , but the result remains flawed. What am I doing wrong in the iteration?

JS Code:

document.querySelectorAll('.audioz').forEach(item => {
    item.addEventListener('keydown', function(e) {
    const ss = document.querySelector(`audio[data-key="${e.keyCode}"]`);
    console.log(ss);
    ss.play();
})})

HTML:

  <audio class="audioz" data-key="65" src="sounds/clap.wav"></audio>
  <audio class="audioz" data-key="83" src="sounds/hihat.wav"></audio>
  <audio class="audioz" data-key="68" src="sounds/kick.wav"></audio>
  <audio class="audioz" data-key="70" src="sounds/openhat.wav"></audio>
  <audio class="audioz" data-key="71" src="sounds/boom.wav"></audio>
  <audio class="audioz" data-key="72" src="sounds/ride.wav"></audio>
  <audio class="audioz" data-key="74" src="sounds/snare.wav"></audio>
  <audio class="audioz" data-key="75" src="sounds/tom.wav"></audio>
  <audio class="audioz" data-key="76" src="sounds/tink.wav"></audio>

You are currently adding a keydown event listener to each audio tag. However, the audio tag is hidden, so you can't execute the keydown event on it. Thus, your code will not work.

Add the event listener to the document instead.

 document.addEventListener('keydown', function(e) { const ss = document.querySelector(`audio[data-key="${e.keyCode}"]`); console.log(ss); ss.play(); })
 <audio class="audioz" data-key="65" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio> press the A key

You can attach a listener to the parent element for each <audio> . This avoids some pollution of events at the document level.

 const audiozResults = document.getElementsByClassName("audioz"); for (const result of audiozResults) { const dataKey = +result.getAttribute("data-key"); result.parentElement.addEventListener("keydown", evt => { if (evt.keyCode === dataKey) { result.play(); } }); }
 <audio class="audioz" data-key="65" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"></audio> press the A key

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