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

jQuery: When parent element is clicked, hide child element. When child element is clicked, don't hide it

通过单击页面上的特定按钮,我有一个带有子元素的父元素 displayed/hidden。该按钮只是将样式从 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');
    }
  });
});

为了这个例子,我默认隐藏了子元素。别担心,我不会在生产中这样做。我正在研究如何执行此基本功能。

这是一个 link 演示:jsfiddle

您可以通过将事件绑定到子项并停止传播来实现。

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

可以找到更多信息here

Updated Fiddle

这是已解决问题的更新 fiddle:https://jsfiddle.net/6u39dfxd/1/

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

$('#parent').click(function(event) {
    if($(this).has(event.target).length === 0) {
        $('#child').toggleClass('display');
    }
});

基本上,您会在点击时获得 event.target 并确保它不包含在 parent 元素中。如果有多个 child,您可以得到更具体的信息,但这应该可以解决问题。

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

  $('#parent').click(function(e)
  {
    $('#child').toggle();      
  });
    $("#parent").children().click( function(e) {
    e.stopPropagation();
  });

我想这会解决你的问题。