简体   繁体   中英

Show/hide a div or p when clicking li

I have an ordered list which when each item is clicked it will toggle show/hide a corresponding div however, I am really unsure of how to do this in a mannor that works best. I know how to do it if I give each item an id or class but I'm sure there is a better way than writing lines and lines of code if it was a big list.

Basically what I have is this:

<ol>
  <li id="no1">Money Savings</li>
  <p id="reasonText">
  Some text....
</p>
  <li>Stable Fares</li>
  <p id="reasonText2">
  Some text...</p>
<li>Reason 3</li>
<p id="reasonText3">Some text...</p>

etc....

JQuery:

 $("#no1").click(function(){
     $("#reasonText").slideToggle('slow')

Is there a better way to iterate through each li and show or hide the div that follows other than basically repeating what I have in my jquery?

You can find an example Here :

<script>
$(document).ready(function() {
    $("li").click(function(){
     $(this).find("p").slideToggle('slow');
          });
    });
</script>

Using all classes instead of ids would be a better way of doing this:

<ol>
  <li class="reason">Money Savings <p class="reasonText">Some text....</p></li>
  <li class="reason">Stable Fares <p class="reasonText">Some text...</p></li>
  <li class="reason">Reason 3 <p class="reasonText">Some text...</p></li>
</ol>

The jQuery would then be as follows:

$('.reasonText').hide(); //hide all the reason text
$('.reason').on('click', function() {
  $(this).children('.reasonText').slideToggle('slow');
});

http://jsfiddle.net/XtUFn/

I moved the <p> tags into the <li> tags because only <li> tags can appear in <ol> tags. If you want to keep your markup with the exception of changing ids to classes.

<ol>
  <li class="reason">Money Savings</li>
  <p class="reasonText">Some text....</p>
  <li class="reason">Stable Fares</li>
  <p class="reasonText">Some text...</p>
  <li class="reason">Reason 3</li>
  <p class="reasonText">Some text...</p>
</ol>​

The jQuery would be as follows:

$('.reasonText').hide(); //hide all the reason text
$('.reason').on('click', function() {
  $(this).next('.reasonText').slideToggle('slow');
});​

http://jsfiddle.net/XtUFn/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM