Toggling div visibility individually with jQuery
I have a simple jQuery function that toggles a div's visibility when clicked. The problem with the function开发者_开发问答 is that it can't be applied to multiple items on the same page or they all toggle in tandem. Is there a way around this without having to assign a unique class to each instance?
jQuery:
$(function(){
$(".toggleThis").click(function(){
$(".hiddenText").slideToggle("fast");
$(this).html(function(i,html) {
if (html.indexOf('+') != -1 ){
html = html.replace('+','-');
} else {
html = html.replace('-','+');
}
return html;
})
});
});
html:
<p class="toggleThis">Blah blah + <p>
<div class="hiddenText">
<p>Blah blah</p>
</div>
css:
.hiddenText {display: none;}
Thanks!
Instead of this:
$(".hiddenText").slideToggle("fast");
Use this:
$(this).next(".hiddenText").slideToggle("fast");
This approach finds it relatively to the clicked element (using .next()
), rather than all class="hiddenText"
. If there are elements in-between that aren't in your example, use .nextAll(".hiddenText:first")
instead.
精彩评论