问题
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...
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/1719558/jquery-toggle-on-each