切换CSS类,但在新的单击后禁用其他元素的类


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

我已经从数组动态生成缩略图来切换页面的背景图像:

<?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" />');
            }
        ?>

我想给缩略图添加一个"current"类,当它是选中的/活动的背景时:

$('#bkgrSelector img').toggleClass(current, addOrRemove);

jQuery的toggleClass应该可以做到这一点,但是我想要在选择新图像时清除先前点击图像的类。

我该怎么做呢?

是否有一个更好的方式通过PHP或jQuery切换图像缩略图上的当前类?

来自PHP数组的后渲染位如下所示:

<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" />

从所有其他图像中删除共同的class,然后重新应用于所选图像

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

让所有缩略图具有一个共同的类,例如thumb。然后,您可以选择所有thumb映像,并关闭current类。然后为选中的文件打开:

//make no thumb have the current class
$('img.thumb').removeClass('current');
//Add the class to your selected item
$selected.addClass('current'); 

您需要在循环中添加thumb类:

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" />');
}

在添加到新图像之前,只需从现有图像中删除该类。

与jQuery

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