如何使用jquery + CSS过滤图像

时间:2012-11-13 16:30:08

标签: jquery image list filtering

所以我有一个来自mysql表的列表。 示例:http://i.imgur.com/MPJSR.png

此列表包含具有ID的特定类别。 获取类别和图像之间的链接。我为每个图像提供了与列表中的类相同的className 恩。

(e.g  <a href="#" class="1">Logo</a>  and <img class="1" src="#" />

在JQuery中编写此代码的最佳方法是什么?

我开始编写一些jQuery代码,但很快发现它是垃圾。

$(document).ready(function(){    
  $(".1").click(function(event){
    $('img.2').addClass("white");        
    $('img.3').addClass("white");        
    $('img.4').addClass("white");
    $('img.5').addClass("white");     
    $('img.6').addClass("white");
    $('img.7').addClass("white");        
    $('img.8').addClass("white");        
    $('img.9').addClass("white");
    $('img.10').addClass("white");
    $('img.11').addClass("white");
    $('img.12').addClass("white");
    $('img.13').addClass("white");    
   });
});

所以我向你们提出的问题是......如果不编写100行丑陋代码,最好的办法是什么。

2 个答案:

答案 0 :(得分:1)

你可以为每个dom元素添加多个类,jquery仍然可以正确找到它。 您需要为所有图片分配其他类,例如class="1 thumb_imageclass="2 thumb_image,然后只需使用jquery not选择器:$('.thumb_image:not("1")').addClass("white");

答案 1 :(得分:0)

如果我正确理解这个问题,我认为这应该可以解决问题。

<script type="text/javascript">
    $(document).ready(function(){    
      $("#category a").click(function(e){
            e.preventDefault();
            var clicked_class = $(this).attr('class');

        $('img').each( function() {
            var image = $(this);

            if( image.hasClass( clicked_class ) ) {
                image.removeClass( 'white' );
            } else {
                image.addClass( 'white' );
            }

        });


       });
    });
</script>

首先,我们将click事件添加到#category div中的锚点。单击它们后,我们将获取所单击锚点的类,然后使用该类与每个图像进行比较。如果图像共享该类,我们使用white类更新它,否则我们删除white类,前一个操作添加了它。