小编Fra*_*cJ3的帖子

jQuery:单击父元素时,隐藏子元素.单击子元素时,不要隐藏它

我有一个带有子元素的父元素,通过单击页面上的特定按钮显示/隐藏它.该按钮只是将样式从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>
Run Code Online (Sandbox Code Playgroud)

这是jQuery:

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

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

为了这个例子,我默认隐藏了子元素.别担心,我不会在生产中这样做.我正在努力弄清楚如何做这个基本功能.

这是一个演示它的链接:jsfiddle

html javascript jquery click toggleclass

2
推荐指数
1
解决办法
943
查看次数

标签 统计

click ×1

html ×1

javascript ×1

jquery ×1

toggleclass ×1