Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...