【问题标题】:Jquery: select only one class onclick - not allJquery:仅选择一个类 onclick - 不是全部
【发布时间】:2016-05-24 15:10:07
【问题描述】:

我正在尝试在单击时为某些图像设置特定的 css 类。

这是我的代码:

<%= image_tag ('snapchat.png'), class: "img-rounded", id: "icon-hover", width: "50px" %>
<%= image_tag ('tinder.png'), class: "img-rounded", id: "icon-hover", width: "50px" %>
<%= image_tag ('tumblr.png'), class: "img-rounded", id: "icon-hover", width: "50px" %>

还有我的 jquery:

$(document).on('click', '.img-rounded', function (){
      $('.img-rounded').css({
        '-webkit-filter':'grayscale(0%)',
        'filter':'grayscale(0%)',
      });
    });

这个功能很好用,问题是当我点击一张图片时,它会将css属性赋予所有其他图片。我怎么能一次只定位一个元素?

感谢您的帮助。

编辑:我的图像被包裹在这样的父元素中:

<b href="" class="wechat" id="icon-hover" style="text-decoration:none">
  <%= image_tag ('wechat.png'), class: "img-rounded", id: "icon-hover", width: "50px" %>
</b> 

因此,即使使用“this”处理程序,它也不会响应:

$(document).on('click', '.img-rounded', function (){
      $(this).css({
        '-webkit-filter':'grayscale(0%)',
        'filter':'grayscale(0%)',
      });
    });

【问题讨论】:

  • 在处理程序中使用$(this)$('.img-rounded').css({ ==> $(this).css({。我建议您使用 CSS 类并使用 .addClass('className) 方法添加该类。

标签: javascript jquery html css ruby


【解决方案1】:
$(document).on('click', '.img-rounded', function (){
      $(this).css({
        '-webkit-filter':'grayscale(0%)',
        'filter':'grayscale(0%)',
      });
    });

【讨论】:

  • 谢谢!!当图像未包含在父元素中时,它运行良好。我编辑了我的问题,你有什么想法吗?我尝试更新 jquery 但它不起作用。
  • $('img.img-rounded).on('click',function (){ $(this).css({ '-webkit-filter':'灰度(0%)' , '过滤器':'灰度(0%)', }); });您可以尝试使用限制性选择器
  • 你能提供一个小提琴你的问题吗?
  • 哇,这是问题的父元素的 id,混淆了 jquery。都好。谢谢!
【解决方案2】:
$(this).css({
    '-webkit-filter':'grayscale(0%)',
    'filter':'grayscale(0%)',
});

这意味着您将当前对象分配给一个名为 $this 的变量。这不是关键字。

【讨论】:

    猜你喜欢
    • 2013-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2018-10-12
    • 1970-01-01
    相关资源
    最近更新 更多