开发者

jQuery - Add/Remove class based on selected item in list

I have a very basic list in HTML:

<ul id="thumbselector">
    <li><img src="http://placekitten.com/80/80"/></li>
    <li><img src="http://placekitten.com/81/81"/></li>
    <li><img src="http://placekitten.com/g/80/80"/></li>
    <li><img src="http://placekitten.com/g/81/81"/></li>
    <li><img src="http://placekitten.com/g/82/82"/></li>
    <li><img src="http://placekitten.com/g/81/82"/></li>
    <li><img src="http://placekitten.com/80/80"/></li>
    <li><img src="http://placekitten.com/81/81"/></li>
    <li><img src="http://placekitten.com/g/80/80"/></li>
    <li><img src="http://placekitten.com/g/81/81"/></li>
    <li><img src="http://placekitten.com/g/82/82"/></li>
    <li><img src="http://placekitten.com/g/81/82"/></li>                            
</ul>

Then im using toggleClass to add an .active class to the img when its clicked:

$('#thumbselector img').click(function() {
  $(this).toggleClass('active');
}); 
开发者_Go百科

However I want each of the images to be aware of each other, so when I select one image and give it the .active class - If I then select another image I want to make sure any previous image with the .active class has it removed.

Any ideas?


Why not just remove the active class from all of them first instead? :

$('#thumbselector img').click(function() {
  $('#thumbselector img').removeClass('active');    
  $(this).addClass('active');
}); 


Yoo

http://api.jquery.com/toggleClass/

$('#foo').toggleClass(className, addOrRemove);

is equivalent to:

if (addOrRemove) {
    $('#foo').addClass(className);
  }
  else {
    $('#foo').removeClass(className);
  }


This should work:

$('#thumbselector img').click(function() {
  $(this).siblings().removeClass('active');
  $(this).addClass('active');
});


$('#thumbselector img').click(function() {
  $('#thumbselector .active').removeClass('active');
  $(this).toggleClass('active');
});

Demo here: http://jsfiddle.net/fermin/5JAUh/


Simply remove the class from all sibling elements:

$('#thumbselector img').click(function() {
 $(this).parent().siblings().children().removeClass('active');
 $(this).toggleClass('active');
});

See it in action here: http://jsfiddle.net/kvhWD/


You need to use the LIVE with click not just CLICK since you are dynamically adding/removing a class. See my example:

$('#thumbselector img').live('click', function() {
  $('#thumbselector img').removeClass('active');    
  $(this).addClass('active');
}); 


Here is solution for this problem:

$('#thumbselector img').on("click", function(){
    if ($(this).hasClass('active')) {
        $(this).removeClass('active');
    } else {
        $(this).addClass('active');
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜