2014-04-02 63 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/