jQuery toggle opens all divs instead of just the next
I am using some jQuery to toggle the visibility of some div's. The toggle occurs on click and should only affect one div. The开发者_C百科 problem is that if there are multiple divs, they are all toggled on/off instead of just the one a user is trying to toggle. I think I need to use the 'next' function but can't get it working. Here is my jQuery:
jQuery(function(){
jQuery(".toggle").click(function(){
jQuery(".hiddenText").slideToggle("fast");
jQuery(this).html(function(i,html) {
if (html.indexOf('More') != -1 ){
html = html.replace('More','Less');
} else {
html = html.replace('Less','More');
}
return html;
}).find('img').attr('src',function(i,src){
return (src.indexOf('plus.gif') != -1)? '/minus.gif' :'/plus.gif';
});
});
});
html:
<p class="toggleText">More Info <img src="/plus.gif"></p>
<div class="hiddenText">
blah blah
</div>
Any tips? Thanks!
For what it's worth, you were right, you do have to use1 next()
:
$(document).ready(
function(){
$('.toggleText').click(
function(){
$(this).next('.hiddenText').toggle();
}
);
}
);
Demo at JS Fiddle.
As pointed out, by @Polyhedron, in the comments, next()
would work, possibly better, without the selector, targetting the next sibling element of $(this)
.
Demo of the plain ol' next()
, at JS Fiddle.
- Well, you don't have to, but you can.
I believe the problem stems from the use of classes as your selector
jQuery(".toggle").click() says when an element with the class to toggleText is clicked jQuery(".hiddenText").slideToggle //Select all elements with a class of .hiddenText and slideToggle this is why all you’re the divs are opening.
Instead of jQuery(".hiddenText").slideToggle("fast");
Try $(this).next(".hiddenText").slideToggle("fast");
精彩评论