gpt4 book ai didi

javascript - HTML5 data-* 属性上的 querySelector() 函数出错

转载 作者:太空宇宙 更新时间:2023-11-04 01:25:38 25 4
gpt4 key购买 nike

我正在尝试使用 Vanilla Js 创建一架简单的钢琴,其中包含所有声音,例如 Do、Re、Mi 等。我收到有关 data-* 属性的 querySelector 函数的错误。这是我的代码的相关部分。

let keyArr = document.querySelectorAll(".musicKey");
var audioKeyProp;
keyArr.forEach(function(item) {
let tempVal = item.getAttribute('data-key');
audioKeyProp[tempVal] = document.querySelector(`audio[data-key=${tempVal}]`);

//For debugging
console.log(audioKeyProp[tempVal]);
});
<body>
<div id="main-div">
<div class="keys">
<div data-key="100" class="musicKey">
<p>D</p><span>(Do)</span></div>
<div data-key="114" class="musicKey">
<p>R</p><span>(Re)</span></div>
<!--there are more such div. To make it simple I only mentioned two -->
</div>
</div>
<audio data-key="100" src="audio/do.mp3" type="audio/mpeg"></audio>
<audio data-key="114" src="audio/re.mp3" type="audio/mpeg"></audio>
<!--there are more such audio elements. To make it simple I only mentioned two -->
</body>

我想在每次按键时发出声音。首先我想将每个音频元素与相应的键相关联。

我收到错误,例如,

"soundBox.js:7 Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': 'audio[data-key=100]' is not a valid selector."

你能说说我错过了什么吗?我不能对两个不同的元素(在我的例子中是 div 和音频)使用 data-key 属性吗?我使用的是 Chrome 浏览器。

最佳答案

将属性值用引号括起来,参见 Attribute selectors

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

let keyArr = document.querySelectorAll(".musicKey");
var audioKeyProp;
keyArr.forEach(function(item) {

//console.log(item);
let tempVal = item.getAttribute('data-key');
console.log(document.querySelector(`audio[data-key="${tempVal}"]`));
});
<div id="main-div">
<div class="keys">
<div data-key="100" class="musicKey">
<p>D</p><span>(Do)</span></div>
<div data-key="114" class="musicKey">
<p>R</p><span>(Re)</span></div>
<!--there are more such div. To make it simple I only mentioned two -->
</div>
</div>
<audio data-key="100" src="audio/do.mp3" type="audio/mpeg"></audio>
<audio data-key="114" src="audio/re.mp3" type="audio/mpeg"></audio>

关于javascript - HTML5 data-* 属性上的 querySelector() 函数出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48188308/

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