简体   繁体   中英

Targeting a clicked element with jquery

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?

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" />

Use the toggleClass method. Add the styling to the css class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM