3 回答
TA贡献1770条经验 获得超3个赞
您需要双击,因为在内addEventListener()
联点击处理程序中使用附加事件处理程序。
我建议您使用DOMContentLoaded
事件和唯一附加事件处理程序addEventListener()
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
const close = document.querySelector('.popup__close');
const popup = document.querySelector('.popup');
close.addEventListener('click', function() {
popup.style.opacity = '0';
});
});
并且不需要丑陋的内联点击处理程序和函数hidePopup(),删除它们
TA贡献1810条经验 获得超5个赞
删除对 addEventListener 的无关调用,并简单地将元素隐藏在单击事件处理程序中。
function hidePopup() {
const close = document.querySelector('.popup__close');
const popup = document.querySelector('.popup');
popup.style.opacity = '0';
}
TA贡献1829条经验 获得超6个赞
在函数 hidePopup 中,注意您在函数第一次运行时“addEventListener”,
当您添加 EventListener 时,不会使函数运行!您分配监听器,以便稍后如果单击,它将运行您在监听器中分配的功能。
如果您使用 addEventListener,则无需再使用 onClick 属性来调用该函数...
我看到您的目标是在单击关闭按钮时隐藏内容,按照您的代码,有两种方法:
第一种方式
//you only need to select once
const popup = document.querySelector('.popup');
function hidePopup() {
popup.style.opacity = '0';
}
//additional function if you want to show pop up
function showPopup() {
popup.style.opacity = '1';
}
<div class="popup">
<span class="popup__close" onclick="hidePopup()">
<i class="fas fa-lg fa-times">X</i>
</span>
<h3 class="popup__heading">
Check our newsletter!
</h3>
<p class="popup__text u-margin-bottom-xs">
Register to our newsletter to see the newest offers!
</p>
<a href="#" class="btn btn--small btn--rounded">Register</a>
</div>
<Br><Br><br>
<span class="popup__show" onclick="showPopup()">
click me to show pop up
</span>
第二种方式
//select both button and Popup
const popup = document.querySelector('.popup');
const close = document.querySelector('.popup__close');
close.addEventListener('click', function() {
popup.style.opacity = '0';
});
const show = document.querySelector('.popup__show');
show.addEventListener('click', function() {
popup.style.opacity = '1';
});
<div class="popup">
<span class="popup__close">
<i class="fas fa-lg fa-times">X</i>
</span>
<h3 class="popup__heading"https://stackoverflow.com/questions/63126988/why-do-i-need-to-click-two-times-to-trigger-an-onclick-function#>
Check our newsletter!
</h3>
<p class="popup__text u-margin-bottom-xs">
Register to our newsletter to see the newest offers!
</p>
<a href="#" class="btn btn--small btn--rounded">Register</a>
</div>
<span class="popup__show">Click here to show pop up</span>
添加回答
举报