问题在 div 元素上添加点击事件,并播放相应的音频元素

Problem add click event on div elements, and play respective audio elements

如何向所有 div 元素添加 click 事件侦听器,以便在单击它们时播放与同一数据键关联的相应音频?

    <div id="click" data-key="65" class="key">
        <kbd>A</kbd>
        <span class="sound"> HeyHey </span>
    </div>
    <div id="click" data-key="83" class="key">
        <kbd>S</kbd>
        <span class="sound">Dungeon Master</span>
    </div>
    <div id="click" data-key="68" class="key">
        <kbd>D</kbd>
        <span class="sound"> Yamite </span>
    </div>
    <div id="click" data-key="70" class="key">
        <kbd>F</kbd>
        <span class="sound"> Nya </span>
    </div>
    <div id="click" data-key="71" class="key">
        <kbd>G</kbd>
        <span class="sound"> AOT </span>
    </div>
    <div id="click" data-key="72" class="key">
        <kbd>H</kbd>
        <span class="sound"> Motivation </span>
    </div>
    <div id="click" data-key="74" class="key">
        <kbd>J</kbd>
        <span class="sound"> NikoChan </span>
    </div>
    <div id="click"  data-key="75" class="key">
        <kbd>K</kbd>
        <span class="sound"> A </span>
    </div>
    <div id="click" data-key="76" class="key">
        <kbd>L</kbd>
        <span class="sound"> MaxVolume </span>
    </div>
function removeTransition(e) {
    if (e.propertyName !== 'transform') return;
    e.target.classList.remove('playing');
}

function playSound(e) {
    const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
    const key = document.querySelector(`div[data-key="${e.keyCode}"]`);
if (!audio) return;

key.classList.add('playing');
audio.currentTime = 0;
audio.play();
}

function playcclickAudio(e) {
    const audio = document.querySelector('audio')
    if (!audio) {
        return
    }
    audio.play()
    audio.currentTime = 0
    this.classList.add ('playing')
}

const keys = Array.from(document.querySelectorAll('.key'));
    keys.forEach(key => key.addEventListener('transitionend', removeTransition, playcclickAudio));
window.addEventListener('keydown', playSound); 

[MyCodePen]https://codepen.io/cstrp/pen/VwbJxKp

添加事件侦听器:

const keys = Array.from(document.querySelectorAll('.key'));
keys.forEach(key =>
{
  key.addEventListener('transitionend', removeTransition, playcclickAudio);
  key.addEventListener('click', playSound);
});

然后在playSound()函数中修复:

    const audio = document.querySelector(`audio[data-key="${e.keyCode||e.target.closest("div.key").dataset.key}"]`);
    const key = document.querySelector(`div[data-key="${e.keyCode||e.target.closest("div.key").dataset.key}"]`);

正如 j08691 所说,元素 ID 应该是唯一的,虽然它不会 破坏 任何东西,但您将无法通过 getElementById()[ 访问这些元素=14=]