jQuery toggle on each?

2019-08-18 19:38发布

im using jquery to toggle some paragraphs. its pretty easy with just one paragraph but say i have a very generic setup. the second paragraph is initially hidden with css.

<p>some text</p>
<p>some more text</p>
<a href="#" class="more">read more</a>

<p>some text</p>
<p>some more text</p>
<a href="#" class="more">read more</a>

problem is that every time i click one of the "read more" links its shows the every second paragraph. i would just want it to show the second paragraph of the one clicked.

very new to jquery...

标签: jquery toggle
2条回答
Juvenile、少年°
2楼-- · 2019-08-18 20:05

First wrap your <p> tags in a div like so:

<div class='toggleable'>
  <p>some text</p>
  <p>some more text</p>
  <a href="#" class="more">more/less</a>
</div>

With some CSS:

.toggleable p {
  display: none;
}

Then the jQuery:

$('.toggleable a.more').click( function() {
  $(this).siblings('p').toggle();
} );

Should handle it.

There are other ways to solve this, of course. Maybe you could put the links outside of the div with the text and then do something like: $('.more').click( function() { $(this).prev().toggle(); } );... Plenty of approaches. Take a look at jQuery's DOM traversal methods.

查看更多
唯我独甜
3楼-- · 2019-08-18 20:07

sorry i think that i may have messed up the structure. its

<p>some text</p> 
<div class="bio> 
<p>some more text</p> 
</div> <a href="#" class="more">read more</a>  

<p>some text</p> 
<div class="bio> 
<p>some more text</p> 
</div> <a href="#" class="more">read more</a> 

i need the first <p> to show always as sort of an experted. the second <p> and any subsequent <p> to only show on click of its specific <a> thanks for the quick response.

查看更多
登录 后发表回答