开发者

Why does jQuery add a class to an image whenI click it even though I haven't specifically asked it to?

开发者 https://www.devze.com 2023-02-25 15:50 出处:网络
Found this recently, but can\'t for the life of me figure out how the \"clickedClass\" bit manages to add the \"selected\" class to the thumbnail...

Found this recently, but can't for the life of me figure out how the "clickedClass" bit manages to add the "selected" class to the thumbnail...

Change "selected" to anything you like and it still works.

        var activeOpacity   = 1.0,
            inactiveOpacity = 0.6,
            fadeTime = 200,
            clickedClass = "selected",
            thumb = "#thumbnailContainer div img";
        $(thumb).fadeTo(1, inactiveOpacity);

        $(thumb).hover(
            function(){
                $(this).stop().fadeTo(fadeTime, activeOpacity);
            },
            function(){
                if(!$(this).hasClass(clickedClass)) {
                    $(this).stop().fadeTo(fadeTime, inactiveOpacity);
                }

        $(thumb).click(function() {
             var clicked, previous;
             clicked = $(this);
             if (!clicked.hasClass(clickedClass)) {
                 previous = $(thumb+'.'+clickedClass);
                 previous.removeClass(clickedClass).fadeTo(fadeTime, inactiveOpacity);
                 clicked.addClass(clickedClass).fadeTo(fadeTime, activeOpacity);
             }
         });

                });

Yes, I know - "it works", but WHY does it work?

Any point开发者_Python百科ers would be greatly appreciated,

JS


This line adds the "selected" class to the thumb.

clicked.addClass(clickedClass).fadeTo(fadeTime, activeOpacity);

here clicked = to the thumbnail and clickedClass = "Selected"


because thumb = "#thumbnailContainer div img"

and $("#thumbnailContainer div img") is a jQuery selector

and this line: $(this).hasClass(clickedClass) checks if the thumbnail has the clickedClass in your case "selected" or any other class.

0

精彩评论

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