Using jquery toggle on individual divs
I'm trying to create a toggl开发者_高级运维e 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?
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.
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.
精彩评论