javascript - jQuery:单击父元素时,隐藏子元素。单击子元素时,不隐藏它

标签 javascript jquery html click toggleclass

我有一个父元素和一个通过单击页面上的特定按钮显示/隐藏的子元素。该按钮只是将样式从 display:none 更改为 display:block,非常简单。子元素以 display:none 开始;

我想在单击父元素时隐藏此元素,但在单击子元素时不隐藏此元素,这是有问题的,因为子元素父元素的一部分。

我看到有 data(); 可以检查元素是否被单击,但这似乎不起作用。

这是 html:

<style>

#parent {width:200px;height:200px;}
#child {display:none;width:50px;height:50px;}
#child.display {display:block;}

</style>

<div id="parent">
Some content
    <div id="child">Some other content</div>
</div>

<button id="clickMe">Toggle Child</button>

这里是 jQuery:

$(function() 
{
  $('#clickMe').click(function() 
  { 
      $('#child').toggleClass('display');
  }); 

  $('#parent').click(function()
  {
     if($('#child').data('clicked') == true )
    {
        // do nothing
    } else 
    {
      $('#child').toggleClass('display');
    }
  });
});

为了这个例子,我默认隐藏了子元素。别担心,我不会在生产中这样做。我只是想弄清楚如何执行此基本功能。

这是它的演示链接:jsfiddle

最佳答案

您可以通过将事件绑定(bind)到 child 并停止传播来实现这一点。

  $('#parent').click(function() {
     $('#child').toggleClass('display');
  });
  $('#child').click(function(e) {
     e.stopPropagation();
  });

可以找到更多信息here

Updated Fiddle

关于javascript - jQuery:单击父元素时,隐藏子元素。单击子元素时,不隐藏它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37489562/

相关文章:

javascript - 尝试修复表头,出现 css 问题

javascript - MomentJS 有时返回无效日期

javascript - Highcharts 固定/ float 轴

jquery - 删除 div 内每个元素的所有属性

javascript - 将 php 作为 "return value"回显到 ajax 调用

html - 一个或两个表格以 div 为中心

javascript - Angular : $scope properties updated with $timeout doesn't seem to update DOM in order

javascript - jQuery:将对象 ["student.course.name"] 转换为对象 ['student' ] ['course' ] ['name' ]

javascript - 鼠标移动 - 在 Firefox 上不起作用

html - 为什么 "position:fixed;"没有将我的页眉保留在同一个位置?