2014-04-02 39 views
0

我想每次删除现有的班级我的元素的我点击的形象。如何删除类,并添加另一个类的jQuery

这是我的HTML:

​​

,这是我的javascript:

$(".technologyImage").click(function() { 
    $(this).removeClass(); 
    $(this).addClass("technologySelected"); 
    $(".technologyImage").css("opacity", "0.4"); 
    $(".technologyImage").css("filter", "alpha(opacity=40)"); 
}); 


$(".technologySelected").click(function() { 
    alert("IMAGE IS ALREADY SELECTED"); 
}); 

我要提醒用户,如果用户单击选定的图像。该代码不能正常工作,每次我点击图片也去了$(".technologyImage")不上$(".technologySelected")

+1

你应该阅读有关如何选择DOM和事件结合的工作。在调用'.click()'方法时,您将'click'处理程序绑定到具有该类的元素。它不会在类更新时自动更新。 –

+0

这是一个良好的开端http://learn.jquery.com/ –

+0

你仍然有这个问题?我使用removeClass与JQM 1.4.3和'removeClass'不能正常工作,每次... – Kallewallex

回答

0

确保您重置透明度上选择影像。

<html> 
<head> 
    <script type="text/javascript" src="./jquery.min.js"></script> 
<script type="text/javascript"> 

    $(document).ready(function() { 
     $(".technologyImage").click(function(){ 
      if($(this).hasClass("technologySelected")){ 
       alert("IMAGE IS ALREADY SELECTED"); 
      }else{ 
       $(".technologySelected") 
        .removeClass("technologySelected");     
       $(".technologyImage") 
        .css("opacity", "0.4") 
        .css("filter", "alpha(opacity=40)"); 
       $(this) 
        .addClass("technologySelected") 
        .css("opacity", "1.0") 
        .css("filter", "alpha(opacity=100)"); 
      } 
     }); 
    }); 
</script> 

</head> 
<body> 

    <img id="Iphone" src="ios.jpg" class="technologyImage"/> 
    <img id="Android" src="android.jpg" class="technologyImage"/> 


</body> 
</html> 
0

试试这个

$(".technologyImage").click(function() { 
     $(this).addClass("technologySelected"); 
     $(".technologyImage").css("opacity", "0.4"); 
     $(".technologyImage").css("filter", "alpha(opacity=40)"); 
     $(this).removeClass(".technologyImage"); 
    }); 

希望这有助于。

+0

这将不会删除technologyImage类! – Kiranramchandran

0

尝试这个

$('div.technologyImage').click(function(){ 

    if($(this).hasClass('technologyImage')){ 
     $(this).addClass('technologySelected'); 
     $(this).css("opacity", "0.4"); 
     $(this).css("filter", "alpha(opacity=40)"); 
     $(this).removeClass('technologyImage'); 
    } 
    else { 
     alert("IMAGE IS ALREADY SELECTED"); 
    } 

}); 

DEMO HERE

0

请检查下面的代码。

JQuery的:

$(".technologyImage").click(function() { 
    var self= $(this); 
    if(self.hasClass("selected")){ 
     alert("IMAGE IS ALREADY SELECTED"); 
    } else { 
     if($(".selected").length > 0) 
      $(".selected").removeClass("selected"); 
     self.addClass("selected"); 
    } 
    $(".technologyImage").addClass("opacityHalf"); 

});

的CSS:

.technologyImage.opacityHalf { 
    opacity:0.4; 
    filter:alpha(opacity=40); 
    } 
    .technologyImage.opacityHalf.selected { 
    opacity:1; 
    filter:alpha(opacity=100); 
    } 

http://jsfiddle.net/r9Yj5/