Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to make a button that toggles between making an img grayscale and normal. I need to find a way to properly target the button if it was clicked. I tried adding a class on click and then targeting that class. I also tried this.

$('.switch').on("click", function() {
    if($(this).attr('data-click-state') == 1) {
        $(this).attr('data-click-state', 0)
        $(this).siblings('img').css("-webkit-filter", "grayscale(100%)");
    } else {
        $(this).attr('data-click-state', 1)
        $(this).siblings('img').css("-webkit-filter", "none");
    }
});

Why the button doesn't toggle between color and grayscale versions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
228 views
Welcome To Ask or Share your Answers For Others

1 Answer

There is nothing wrong with the code you're showing us.

It looks like the problem is in your HTML, or in some part of your JS code that you aren't showing us.

Demo :

$('.switch').on("click", function() {
    if($(this).attr('data-click-state') == 1) {
        $(this).attr('data-click-state', 0)
        $(this).siblings('img').css("-webkit-filter", "grayscale(100%)");
    } else {
        $(this).attr('data-click-state', 1)
        $(this).siblings('img').css("-webkit-filter", "none");
    }
});
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<button class="switch" data-click-state="1">Switch</button><br/><br/>
<img src="http://1.gravatar.com/avatar/81bf1bd14d4465c89ca500001b22cf6e?size=140" />
<img src="http://1.gravatar.com/avatar/e711e151e517ae1b897898928cc7981c?size=140" />

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...