开发者

JQuery switchClass with multiple classes in loop form

I am surprised I can't find a similar question out there. I have an icon element that I need to change when I click on a tab section. There are 6 sections. I have it working to add a class, tried properly using remove class so it doesn't keep adding class upon class. I just can't get it right.

Here is my code:

<script type="text/javascript"> 
$(document).ready(function(){
     $('.changeImage').click(function()
{var rel = $(this).attr('rel');
 $('.image').addClass("image"+rel);
$(this).siblings().removeClass("image"+rel);
            return false;
         })
 });
</script>

I have also tried this:

$('.image').addClass("image"+rel);
$(this).next().find('.image').removeClass("image"+rel);

It doesn't work either.

HTML portions (not including all surrounding code):  

 <div><a href="#" class="changeImage" rel="1"><img class="thumb" src="images/image1_thumb.png" /></a></div>

CSS example:

.image1 {
background:url(images/fast.png) no-repeat;

}

.image2 {background:url(im开发者_如何学JAVAages/peep.png) no-repeat;
}

Is there a more efficient way of swapping out bg images? Is switchClass an option?

I appreciate it.


The way I have it set up is that when you click on the link to a section, it has a defined value in rel that gets added to the class "image"+rel

Since i have 6 different links that will coorespond with css classes image1, image2, image3, etc, i want a general jquery statement that says add the class that is clicked, but remove it OR switch it with the class of the next link that is clicked.

I can get it to add multiple classes, just not properly remove the old while adding the next upon clicking other links.


The line $('.image').addClass("image"+rel); is looking for something with the class image, which I don't see in your code snippet.

In general, you can replace all existing classes with a new one by doing:

$('selector').attr('class', '').addClass('newClass');


You can check out http://api.jquery.com/toggleClass/

Basically you'd do something like $('.changeImage').toggleClass('image2');

This will toggle on/off the .image2 style.


css should be background-image

You can use toggleClass

$(document).ready(function(){
    $("a").click(function(e){
        e.preventDefault();
        $("div",this).toggleClass("img1");
    }          
   );
});

jsFiddle example

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜