我意识到这个问题可能已经得到解答,但我就是无法让它发挥作用。请记住,这在 WordPress 之外运行良好。
I am getting this error when page is loaded up: (index):54 Uncaught TypeError: Cannot read property 'addEventListener' of null at (index):54.
And I am getting this error when Privacy policy is clicked: (index):50 Uncaught TypeError: Cannot read property 'classList' of null at togglePopup ((index):50) at HTMLDivElement.onclick ((index):477)
HTML:
<div class="popup-backdrop"></div>
<div class="popup" onclick="togglePopup()">Privacy policy.
<span class="popuptext" id="myPopup">
Popup text to show up.
</span>
</div>
JS:
const popup = document.getElementById("myPopup");
const backdrop = document.querySelector('.popup-backdrop');
function togglePopup () {
popup.classList.toggle('show');
backdrop.classList.toggle('popup-opened');
};
backdrop.addEventListener('click', closePopup);
function closePopup () {
popup.classList.toggle('show');
backdrop.classList.toggle('popup-opened');
};
我通过 functions.php 文件在 WordPress 中包含了 JavaScript,如下所示:
wp_enqueue_script( 'main-js-file', get_template_directory_uri() . '/js/main.js');
我的其他 JavaScript 也可以使用。
有什么帮助吗?
最佳答案
似乎事件监听器正在尝试在相关 DOM 对象加载之前进行绑定(bind)。此问题的一种可能解决方案是在加载所有对象后添加事件监听器。尝试:
document.onload()=function() {
const popup = document.getElementById("myPopup");
const backdrop = document.querySelector('.popup-backdrop');
backdrop.addEventListener('click', closePopup);
};
或使用 jQuery
jQuery(document).ready(function(){
const popup = document.getElementById("myPopup");
const backdrop = document.querySelector('.popup-backdrop');
backdrop.addEventListener('click', closePopup);
});
关于javascript - 无法让 onclick 事件在 WordPress 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52233211/