When using jQuery's click event on a class, how can I avoid calling the event for all with that class name?
I am sorry for the poorly worded question, but if you look at the code, what I am asking is really quite simple.
$(".toggle").click(function () {
var togg = $(this).attr( 'id' );
if( $(this).text() == 'Read More >>' )
{
$("." + togg).addClass( "myBlurbExpanded" , 2000 );
$("." + togg).removeClass( togg , 2000 );
$(this).text('Read Less >>');
}
else if( $(this).text() == 'Read Less >>' )
{
$(".myBlurbExpanded").addClass( togg , 2000 );
$(".myBlurbExpanded").removeClass( "myBlurbExpanded" , 2000 );
$(this).text('Read More >>');
}
});
My page has a bunch of biographies on different people next to their picture. I do not want the entire bio to be visible, so there is a 'show more' and 'show less' link. The 'show more/less' link has a class of '.toggle'. So every time this click is executed, all of the biographies expand. How can I limit the biography expansion to only the one which is clicked. Am I going about it the wrong way by adding the .toggle class to the link. Thanks!
Thank you for the responses.
First, here is an example of my html
<div class="teamInfo">
<h3 class="lightblue">John Doe</h3>
<p class="lightblue"><strong>Programmer</strong></p>
<div class="myBlurb8">
information about this person
</div>
<a h开发者_StackOverflow社区ref="#" onclick="return false;" id="myBlurb8" class="toggle">Read More >></a>
</div>
Next, I will try to change . + togg to (this) and see what happens.
Cheers!
You need to assign a variable to the click function's event and then use the event.target
instead of this
like so:
$(".toggle").click(function (event) {
var $target = $(event.target);
var togg = $target.attr( 'id' );
if( $target.text() == 'Read More >>' )
{
$("." + togg).addClass( "myBlurbExpanded" , 2000 );
$("." + togg).removeClass( togg , 2000 );
$target.text('Read Less >>');
}
else if( $target.text() == 'Read Less >>' )
{
$(".myBlurbExpanded").addClass( togg , 2000 );
$(".myBlurbExpanded").removeClass( "myBlurbExpanded" , 2000 );
$target.text('Read More >>');
}
});
精彩评论