简体   繁体   English

如何去除子元素的点击事件?

[英]How to remove child element click event?

Need your help on this one.在这方面需要你的帮助。 In navigation bar i have an item called author which shows info about author when clicked, in a form of dropdown.在导航栏中,我有一个名为作者的项目,它在单击时以下拉列表的形式显示有关作者的信息。 The problem is that dropdown is clickable and that makes it disappear.问题是下拉菜单是可点击的,这使得它消失了。 I want to be able to show/close it only in navigation bar.我希望只能在导航栏中显示/关闭它。

<div id = 'Author' class = 'navbarItem'>Author
   <div id = 'authorInfo'>
         // info about author
   </div>

const author = document.getElementById('Author');
const authorInfo = document.getElementById('authorInfo');

author.onclick = () => {
     if(authorInfo.style.display == 'none' || authorInfo.style.display == '')
          authorInfo.style.display = 'block'
     else 
          authorInfo.style.display = 'none';     
}

Have tried setting onclick event of authorInfo to null, that doesn't work.已尝试将 authorInfo 的 onclick 事件设置为 null,但不起作用。

Add the event parameter on listener to test if click was made on containter and not on its child.在侦听器上添加事件参数以测试单击是在容器上而不是在其子容器上进行的。 event.target holds the clicked element. event.target持有被点击的元素。

 const author = document.getElementById('Author'); const authorInfo = document.getElementById('authorInfo'); // You need the event parameter on function author.onclick = function(event) { // Do it only if clicked element is author div, not its child if(event.target == author) { if(authorInfo.style.display == 'none' || authorInfo.style.display == '') authorInfo.style.display = 'block' else authorInfo.style.display = 'none'; } }
 <div id = 'Author' class = 'navbarItem'>Author <div id = 'authorInfo' style="display:none;"> // info about author </div> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM