javascript - 如何去掉子元素的点击事件?

标签 javascript events

在这件事上需要您的帮助。在导航栏中,我有一个名为作者的项目,单击时以下拉列表的形式显示有关作者的信息。问题是下拉菜单是可点击的,这使得它消失。我希望能够仅在导航栏中显示/关闭它。

<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';     
}

尝试过将authorInfo的onclick事件设置为null,但不起作用。

最佳答案

在监听器上添加事件参数,以测试是否在容器上而不是其子容器上进行了单击。 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>

关于javascript - 如何去掉子元素的点击事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61194415/

相关文章:

events - iOS - 通过 View 转发所有触摸

java - 如何一次打印 x 行

javascript - 如何在javascript中对同一元素应用长按事件和双击事件

php - 在特定时间自动安排 php 脚本执行

文件夹上的 C#(outlook 加载项)上下文菜单

javascript - 从对象数组 : Javascript 中获取键

javascript - Firebase 身份验证网络 : how to verify email address

javascript - 语法错误: Unexpected token { in directive angular js

javascript - 如何更新 pouchDB 文档中的单个字段

javascript - 在javascript中访问另一个窗口中窗口的全局变量