使用jQuery定位点击元素 [英] Targeting a clicked element with jquery

查看:76
本文介绍了使用jQuery定位点击元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个在img灰度和正常之间切换的按钮.如果单击了按钮,我需要找到一种正确定位按钮的方法.我尝试在点击时添加一个类,然后定位该类.我也试过了.

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.

问题似乎出在您的HTML或您未向我们显示的JS代码的某些部分.

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

$('.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" />

这篇关于使用jQuery定位点击元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆