【问题标题】:jQuery: When parent element is clicked, hide child element. When child element is clicked, don't hide itjQuery:当父元素被点击时,隐藏子元素。单击子元素时,不要隐藏它
【发布时间】:2016-05-27 17:49:53
【问题描述】:

我有一个父元素和一个子元素,通过单击页面上的特定按钮来显示/隐藏。该按钮只是将样式从 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

【问题讨论】:

    标签: javascript jquery html click toggleclass


    【解决方案1】:

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

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

    更多信息可以找到here

    Updated Fiddle

    【讨论】:

      【解决方案2】:

      这是解决问题的更新小提琴: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 并确保它不包含在父元素中。如果有多个孩子,您可以更具体,但这应该可以解决。

      【讨论】:

        【解决方案3】:
          $('#clickMe').click(function() 
          { 
              $('#child').toggle();
          }); 
        
          $('#parent').click(function(e)
          {
            $('#child').toggle();      
          });
            $("#parent").children().click( function(e) {
            e.stopPropagation();
          });
        

        我想这会解决你的问题。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-05
          相关资源
          最近更新 更多