开发者

Toggling a CSS class but disabling class from other elements after a new click

I've got thumbnails being generated dynamically from an array to toggle a background image for the page:

<?php
            for($i=0; $i < count($imageArray); $i++){
                 echo('<img onclick="changeBig(\''.$imageArray[$i].'\')" src="/lib/img/bkgr/'.$imageArray[$i].'" alt="thumbnail image" width="77" height="44" />');
            }
        ?>

I want to add a class of "current" to the thumbnail image when it is the selected/active background:

$('#b开发者_开发百科kgrSelector img').toggleClass(current, addOrRemove);

jQuery's toggleClass should do the trick, but I would want to clear the class off of previously clicked images when a new one is selected.

How fo I go about doing that?

Is there a better way via PHP or jQuery to toggle the current class on the image thumbnails?

The post-rendered bit from that PHP array is below, as requested:

<div id="bkgrSelector"> 
    <div class="scrollNav"> 
        <a class="prev"></a> 
    </div> 
    <div class="scrollable">   
        <div class="items" id="thumbs"> 
            <img onclick="changeBig('Antipasti.jpg')" src="/lib/img/bkgr/Antipasti.jpg" alt="thumbnail image" width="77" height="44" />


Remove the common class from all other images and then re-apply it to the one selected.

$('#bkgrSelector img').click(function(){
    $('#bkgrSelector img').removeClass('selected');
    $(this).addClass('selected');
});


Have all the thumbnail images have a common class, such as thumb. You can then select all thumb images, and turn the current class off. Then turn it on for the selected one:

//make no thumb have the current class
$('img.thumb').removeClass('current');

//Add the class to your selected item
$selected.addClass('current'); 

You would need to add the thumb class in your loop:

for($i=0; $i < count($imageArray); $i++){
    echo('<img onclick="changeBig(\''.$imageArray[$i].'\')" src="/lib/img/bkgr/'.$imageArray[$i].'" class="thumb" alt="thumbnail image" width="77" height="44" />');
}


Just remove the class from existing images before adding it to the new one.

With jQuery

$("img").click( function() {
    //remove class from existing
    $("img.selected").removeClass('selected');
    //add class for current
    $(this).addClass('selected');
});    
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜