我试过getElementsByClassName它得到了同样的错误,这很奇怪。在我的HTML中,我将<p id="trigger-overlay">
更改为
<p class="trigger-overlay">
错误
function toggleOverlay(){alert('fire');};
var triggerBttn = document.querySelector('trigger-overlay');
triggerBttn.addEventListener( 'click', toggleOverlay );
工作
function toggleOverlay(){alert('fire');};
var triggerBttn = document. getElementById('trigger-overlay');
triggerBttn.addEventListener( 'click', toggleOverlay );
答案 0 :(得分:3)
类选择器应以.
点开头:document.querySelector('.trigger-overlay');
。
MDN: https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors