Can';无法在Javascript中获取要匹配的event.target.id
我在Can';无法在Javascript中获取要匹配的event.target.id,javascript,dom-events,Javascript,Dom Events,我在buttons变量中嵌套了三个按钮,如果单击嵌套元素中的按钮,这些按钮都应该播放特定的歌曲。检查按下哪些按钮的代码为: //buttons variable that the three button elements are nested in const buttons = document.getElementById('music-choice'); //the buttons themselves const canonButton = document.getElementBy
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();
}
}
但是,每次尝试运行此代码时,控制台中都会显示以下错误消息:
未捕获的TypeError:无法读取未定义的属性“target”
在MusicLayer(index.js:23)
索引js:20
当我使用这些事件对象的控制台日志时,它说event.target.id是
moonlightButton
,因此我假设它等于字符串moonlightButton
将触发那些if和else if语句,但事实并非如此。我已经尝试过使用类名和值,但到目前为止,它们中的任何一个都没有成功。我是Javascript新手,因此非常感谢您的帮助。正如vlaz所指出的,我试图将一个不存在的参数传递给我的事件侦听器 按钮。addEventListener('click',MusicLayer(event))
这是不正确的,您正在执行传递不存在的参数event
的函数。添加listener->按钮时只需使用函数引用。addEventListener('click',MusicLayer)
解决了这个问题。我想我还是得把活动的概念完全弄清楚。非常感谢你向我解释。