簡體   English   中英

jQuery:單擊父元素時,隱藏子元素。 單擊子元素時,不要隱藏它

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

我有一個父元素和一個子元素,通過單擊頁面上的特定按鈕可以顯示/隱藏該子元素。 該按鈕只是將樣式從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');
    }
  });
});

為了這個示例,默認情況下我隱藏了child元素。 不用擔心,我不會在生產中這樣做。 我正在研究如何執行此基本功能。

這是它的演示鏈接: jsfiddle

您可以通過將事件綁定到子級並停止傳播來實現。

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

更多信息可以在這里找到

更新小提琴

這是一個已解決問題的更新小提琴: 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,並確保其未包含在父元素中。 如果有一個以上的孩子,您可能會更加具體,但這應該可以解決。

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

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

我認為這可以解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM