简体   繁体   中英

Using jquery toggle on individual divs

I'm trying to create a toggle effect using + and - boxes for showing and hiding divs. And example http://theodin.co.uk/tools/tutorials/jqueryTutorial/index.html

This is the script I'm using

$(function(){
        $('.block').hide();
            $('#show').toggle(function(){
                    $('.block').show(); 
                    $(this).attr("src","images/minus.jpg" );
            },function(){
                $('.block').hide(); 
                $(this).attr("src", "images/plus.jpg" );
            });
    });

The HTML

<div id="show"> Open <img id="show" src="images/plus.jpg"/> </div>
    <div class="block"> 
        Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    </div>  

It works fine with one div but I have multiple and when I click one, they all show. Is there a way to toggle them individually using the code I have?

You're changing the src of the #show element, when you should be changing it on its child <img> .

$(function() {
    $('.block').hide();
    $('#show').toggle(function(){
         $('.block').show(); 
         $(this).children('img').attr("src","images/minus.jpg" );
    },function(){
         $('.block').hide(); 
         $(this).children('img').attr("src", "images/plus.jpg" );
    });
});

This uses .children() to get the child <img> element so you can change its source.

Also, the <img> has the same ID as its parent. This is not allowed. IDs must be unique.

Change the show ID to a class like this:

<div class="show"> Open <img src="images/plus.jpg" /> </div>
<div class="block">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div>  

<div class="show"> Open <img src="images/plus.jpg" /> </div>
<div class="block">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div>  

Then the jQuery becomes:

$('.show').toggle(function(){
  $(this).next('.block').show(); 
  $(this).children("img").attr("src","images/minus.jpg" );
},function(){
  $(this).next('.block').hide(); 
  $(this).children("img").attr("src", "images/plus.jpg" );
});

Here's an example.

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