事件 Javascript 当我按下一个键时有声音

Event Javascript with sound when I press a key

我用的是datakey,一按就发出声音

你能解释一下为什么我的代码不起作用吗?

<!DOCTYPE html>
<html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>day1 javascript</title>    
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" href="minireset.css">
    </head>

    <body>

        <div class="keys">
            <div class="key" data-key="65"><kbd>A</kbd><span class="sound"><br/>Clap</span></div>
            <div class="key" data-key="90"><kbd>Z</kbd></div>
            <div class="key" data-key="69"><kbd>E</kbd></div>
            <div class="key" data-key="82"><kbd>R</kbd></div>
            <div class="key" data-key="84"><kbd>T</kbd></div>
            <div class="key" data-key="89"><kbd>Y</kbd></div>
            <div class="key" data-key="85"><kbd>U</kbd></div>
            <div class="key" data-key="73"><kbd>I</kbd></div>
            <div class="key" data-key="79"><kbd>O</kbd></div>
            <div class="key" data-key="80"><kbd>P</kbd></div>
        </div>

        <audio data-key="65" src="sound/clap.wav"></audio>

        <script>
            window.addEventListener('keydown', function(e){
                var key=e.keyCode;
                const audio = document.querySelector('audio[data-key=' +key+']');
                if (!audio)  return;

                audio.play();
            });

        </script>
    </body>
</html>

我有这个错误:

index.html:30 Uncaught DOMException: Failed to execute 'querySelector' on 'Document': 'audio[data-key=65]' is not a valid selector.

您需要像这样添加额外的引号:

document.querySelector('audio[data-key="' +key+'"]')

您的查询选择器的结果是,

document.querySelector('audio[data-key=' + key +']');
// audio[data-key=45]

这里你缺少 '' 的值,所以你的代码应该是这样的,

document.querySelector('audio[data-key="' + key +'"]');
// audio[data-key="45"]

试试看这两个答案

Playing audio with Javascript?

How to register document.onkeypress event

也许你应该有这样的东西:

var audio11 = new Audio('audio_file.mp3');
var audio12 = new Audio('audio_file.mp3');
var audio13 = new Audio('audio_file.mp3');


document.addEventListener("keydown", keyDownTextField, false);

    function keyDownTextField(e) {
      var keyCode = e.keyCode;
      if(keyCode==12) {audio12.play();}
      if(keyCode==11) {audio13.play();}
      if(keyCode==110) {audio110.play();}       
      else {audio12.play();}
}

取决于我实际使用了多少自动文件Switch Case

我对键码帮助不大:http://gcctech.org/csc/javascript/javascript_keycodes.htm