jQuery toggle on each?

筅森魡賤 提交于 2019-12-11 16:53:59

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!