[英]why click with delegate event not working?
I tried to bind document to delegate my click event if user click out of the part of loginpage it should be disappear or be removed, but except signinpage when I clicked loginpage the others part it still be removed(like input).我试图绑定文档以委托我的点击事件,如果用户点击登录页面的一部分,它应该消失或被删除,但除了登录页面,当我点击登录页面时,其他部分仍然被删除(如输入)。 it should bubble to the div signinpage or it's not working like that?
它应该冒泡到 div 登录页面还是不能那样工作? it have confused me two days, plz help me to fix it.
这让我困惑了两天,请帮我解决它。
const loginbtn = document.getElementById('loginbtn')
const whitepart = document.getElementById('whitepart')
const loginpage = document.createElement('div')
loginpage.id = "loginpageid"
loginbtn.addEventListener('click', () => {
whitepart.appendChild(loginpage)
loginpage.innerHTML = `
<div id="sign_in_out" >
<div id="logopaint">
<img src="../image/FE_logo-2.png" alt="sorry, something worng!">
</div>
<form id="forclick">
<input type="email" name="user_email" id="mail" placeholder="Email" autocomplete="email">
<input type="password" name="user_password" id="password" placeholder="Password" autocomplete="current-password">
</form>
</div>`
const signinpage = document.getElementById('sign_in_out')
if (!!signinpage) {
document.addEventListener('click', (e) => {
if (e.target !== signinpage) {
loginpage.removechild(signinpage)
}
})
}
Inside your click listener change e.target !== signinpage
to e.target.closest("#sign_in_out")
, so if the user click inside the login page, the e.target.closest("#sign_in_out")
will return the sign_in_out
div reference, otherwise the reference will be null.在您的点击侦听器中,将
e.target !== signinpage
更改为e.target.closest("#sign_in_out")
,因此如果用户在登录页面内单击,则e.target.closest("#sign_in_out")
将返回sign_in_out
div 引用,否则引用将为空。
When you use
e.target
it can be anything, it can beimg, form, or input
, theevent.target
returns the item on which user clicked.当您使用
e.target
它可以是任何东西,可以是img, form, or input
,event.target
返回用户单击的项目。 The target property of the Event interface is a reference to the object that dispatched the event.Event 接口的 target 属性是对调度事件的对象的引用。
document.addEventListener('click', (e) => {
if (e.target.closest("#sign_in_out") === null) {
loginpage.removechild(signinpage)
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.