hasClass不工作,在每个相册框上显示div单击以通过替换类来显示图像

时间:2014-01-06 10:43:10

标签: jquery html css

<div class="album 1"></div>
<div class="album 2"></div>
<div class="album 3"></div>
<div class="album 4"></div>

<script>

$('.album').click(function(){
   $('.album').each(function(){
  $('enlarge-album-box').css('display','none');

  if($(this).hasClass('1')){
     alert('this is');
     $('.enlarge-album-box').show().css('background','red');
  }
  else if($(this).hasClass('2')){
     alert('now this');
     $('.enlarge-album-box').show().css('background','green');
  }
  });

});
</script>

我正在创建一个相册框,通过点击每个相册类型在开场框中显示相关图像,iv'e给每个相册一个不同的类,如1 2 3 4,所以我想在放大框中显示不同的属性点击每个不同的班级

4 个答案:

答案 0 :(得分:3)

不需要每个循环,用于隐藏元素的选择器也是错误的

jQuery(function () {
    $('.album').click(function () {
        $('.enlarge-album-box').hide();

        if ($(this).hasClass('1')) {
            $('.enlarge-album-box').show().css('background', 'red');
        } else if ($(this).hasClass('2')) {
            $('.enlarge-album-box').show().css('background', 'green');
        }
    });
})

演示:Fiddle

答案 1 :(得分:0)

$('enlarge-album-box').css('display','none');

应该是

$('.enlarge-album-box').css('display','none'); 

$('#enlarge-album-box').css('display','none'); //matter what is in your case id or class

答案 2 :(得分:0)

<div class="album one"></div>
<div class="album two"></div>
<div class="album three"></div>
<div class="album four"></div>

<script>

$('.album').click(function(){
   $('.album').each(function(){
  $('enlarge-album-box').css('display','none');

  if($(this).hasClass('one')){
     alert('this is');
     $('.enlarge-album-box').show().css('background','red');
  }
  else if($(this).hasClass('two')){
     alert('now this');
     $('.enlarge-album-box').show().css('background','green');
  }
  });

});

答案 3 :(得分:0)

试试这个

$(function () {
        $('.album').on('click',function (e) {
            e.stopPropagation();
            $('.enlarge-album-box').hide();

            if ($(this).hasClass('1')) {
                $('.enlarge-album-box').show().css('background', 'red');
            } else if ($(this).hasClass('2')) {
                $('.enlarge-album-box').show().css('background', 'green');
            }
        });
    })
    $('.enlarge-album-box').click(function(e){
        e.stopPropagation();
    });
    $(document).click(function(){
         $('.enlarge-album-box').slideUp();
    });

DEMO