gpt4 book ai didi

javascript - 按下按键时发出声音的 JavaScript 事件

转载 作者:行者123 更新时间:2023-11-28 16:56:59 25 4
gpt4 key购买 nike

我使用 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+'"]')

关于javascript - 按下按键时发出声音的 JavaScript 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58893433/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com