【发布时间】:2018-09-13 04:45:22
【问题描述】:
我在buttons 变量中嵌套了三个按钮,如果单击嵌套元素中的按钮,它们都应该播放特定歌曲。检查按下了哪些按钮的代码是:
//buttons variable that the three button elements are nested in
const buttons = document.getElementById('music-choice');
//the buttons themselves
const canonButton = document.getElementById('canonButton');
const moonlightButton = document.getElementById('moonlightButton');
const _40thButton = document.getElementById('40thButton');
//variables connected to the audio elements
const canonMusic = document.querySelector('audio[id="canon"]')
const moonlightMusic = document.querySelector('audio[id="moonlight"]')
const _40thMusic = document.querySelector('audio[id="40th"]')
buttons.addEventListener('click', musicPlayer(event)); //this is js.20
function musicPlayer(event) {
if (event.target.id === 'moonlightButton') { //this is js.23
moonlightMusic.play();
}
else if (event.target.id === 'canonButton') {
canonMusic.play();
}
else if (event.target.id === '40thButton') {
_40thMusic.play();
}
}
但是,每次我尝试运行此代码时,我都会在控制台中收到以下错误消息:
未捕获的类型错误:无法读取未定义的属性“目标” 在音乐播放器 (index.js:23) 在 index.js:20
当我使用这些事件对象的控制台日志时,它说 event.target.id 是 moonlightButton,所以我假设让它等于字符串 moonlightButton 会触发那些 if 和 else if 语句但事实并非如此。我已经尝试过使用类名和值,但到目前为止都没有运气。我是 Javascript 新手,因此我们将不胜感激。
【问题讨论】:
-
buttons.addEventListener('click', musicPlayer(event))这是不正确的,您正在执行函数传入一个不存在参数event。添加监听器时只需要使用函数引用->buttons.addEventListener('click', musicPlayer) -
哈哈解决了。我想我还是得把活动概念完全搞清楚。非常感谢您向我解释。
标签: javascript dom-events