简体   繁体   English

无法弄清楚为什么它不起作用。 javascript调用数据键

[英]Can't figure out why it isn't working. javascript calling data-key

I'm working on a little project since I am a Javascript beginner. 因为我是Javascript初学者,所以我正在做一个小项目。 I have spent some hours on the same problem, and I just can't figure why it doesn't work. 我已经在同一个问题上花费了几个小时,但我无法弄清楚为什么它不起作用。 I would have rather find the problem myself, but I guess it is time to ask for help. 我宁愿自己找到问题,但我想是时候寻求帮助了。

window.addEventListener('keydown', function (e) {
    console.log(e);
    const audio = document.querySelector('audio[data-key="${e.keyCode}"]');
    console.log(audio);

    /* audio.currentTime = 0; 
    if(!audio) return;
    audio.play(); */
});

So I just can't figure out why I doesn't select the data key in my HTML, the console log say the audio is null . 所以我只是想不出为什么我没有在HTML中选择数据键,控制台日志说音频为null

Here is my HTML code: 这是我的HTML代码:

  <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Page Title</title>
    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />

</head>
<body>


    <div id="main">
        <div data-key="68" class="key">
            <p>Press D for Dogs</p>
        </div>
        <div data-key="67" class="key">
            <p>Press C for Cats</p>
        </div>
        <div data-key="18" class="key">
            <p>Press P for Pigs</p>
        </div>
        <div data-key="70" class="key">
            <p>Press F for Frogs</p>
        </div>
        <div data-key="69" class="key">
            <p>Press E for Elephants</p>
        </div>
        <div data-key="71" class="key">
            <p>Press G for Goats</p>
        </div>
    </div>    

    <audio data-key="68" src="sounds/dog_x.wav"></audio>
    <audio data-key="67" src="sounds/cat_y.wav"></audio>
    <audio data-key="18" src="sounds/pig.wav"></audio>
    <audio data-key="70" src="sounds/frog.wav"></audio>
    <audio data-key="69" src="sounds/elephant.wav"></audio>
    <audio data-key="71" src="sounds/goat.wav"></audio>


    <script src="main.js"></script> 

</body>
</html>

Thanks in advance. 提前致谢。

Your query needs editing: 您的查询需要编辑:

document.querySelector('audio[data-key="${e.keyCode}"]');

There is no such thing as parameter expansion in strings enclosed in single quote marks ( '' ). 有在用单引号(字符串参数扩展没有这样的事'' )。

Either concatenate the correct string like this 像这样连接正确的字符串

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

or use a template string ( MDN ) 或使用模板字符串( MDN

document.querySelector(`audio[data-key="${e.keyCode}"]`);

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

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