jquery从中选择父项,然后选择其子项

时间:2016-09-04 07:51:19

标签: jquery this parent-child parent

我需要选择'this'元素的父元素然后它的孩子你能看到我的代码是否正确吗?

$(this).click(function(){
  $(this).parent('li').child('p').toggle();
  $(this).not(this).parent('li').child('p').toggle('hide');
});

这实际上是一个看起来有点像这个

的html
<ul>
  <li><header>Header 1</header><p>Content 1</p></li>
  <li><header>Header 2</header><p>Content 2</p></li>
</ul>

你能解释一下,如果剧本是否正确吗?

1 个答案:

答案 0 :(得分:1)

var $contents = $("ul p"); // get 'em all! (and use class to be more specific)

$('header').click(function(){
  var $myContent = $(this).closest('li').find('p'); // this content
  $contents.not($myContent).hide();                 // hide all other
  $myContent.toggle();                              // this content toggle
});
ul p{display:none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><header>Header 1</header><p>Content 1</p></li>
  <li><header>Header 2</header><p>Content 2</p></li>
  <li><header>Header 3</header><p>Content 3</p></li>
</ul>

相关问题