开发者

Classes won't swap using jQuery

I'm trying to create something where you click on an image and it simply get's replaced with another image of the same dimensions.

I can almost get this working with the jQuery below, however it isn't changing the classes properly. The 'before' image has a class where :hover changes it's opacity. Once clicked I don't want 开发者_StackOverflow社区the image to do the same, so I have created a second class for the 'after' image. However it just won't change classes.

HTML:

<div id="vote">
  <img src="images/icon-voteheart2.png" class="heart" />
  <h2>12</h2>
</div>

Javascript:

<script type="text/javascript"> 
  $(function() {
    $('.heart').click(function() {
        $(".heart").fadeOut('fast');
        $(".heart").fadeIn('fast');
        $(".heart").attr('src', "images/icon-tick.png");
        $(this).removeClass(".heart");
        $(this).addClass(".heartnew");
        return false;
    });
  });
< /script>


Your class name isnt .heart its just heart. The . infront of class names is only used for CSS selectors, not in add or remove class


Since the heart class is being dynamically generated and removed, you need to use the live function

$('.heart').live("click", function() {
   //etc
});

Additionally, .heart is not the name of the class. You need to change

$(this).removeClass(".heart"); 
$(this).addClass(".heartnew");

to

$(this).removeClass("heart"); 
$(this).addClass("heartnew");


These two lines are wrong.

    $(this).removeClass(".heart");
    $(this).addClass(".heartnew");

When using removeClass() and addClass(), do not include the dot. It should be like this:

    $(this).removeClass("heart");
    $(this).addClass("heartnew");


Your class name is "heart", so your selectors $(".heart") are correct, but when you use the addClass, removeClass, and toggleClass methods, use the actual class name: addClass("heart").

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜