简体   繁体   English

如何通过 class 名称仅获取单击的元素?

[英]How to get only clicked element by class name?

I have some elements with the same class name but I want to get only clicked element class and change it.我有一些具有相同 class 名称的元素,但我只想获取单击的元素 class 并更改它。

    var icon = $('.opener i'); // I want to take this class of only clicked element
   

Function Function

      $('.cate-inner span.opener').on("click", function(){
          var icon = $('.opener i');
        if ($(this).hasClass("plus")) {
          $(this).parent().find('.mega-sub-menu').slideDown();
          $(this).removeClass('plus');
            $(this).addClass('minus');
            icon.removeClass('fa-plus');
            icon.addClass('fa-minus')
        }
});

Try to use context in query尝试在查询中使用上下文

var icon = $('i', $(this));

For better understanding you can check this docs为了更好地理解,您可以查看此文档

Without html it's hard to tell but i will guess than replacing没有 html 很难说,但我猜比更换

var icon = $('.opener i');

by经过

var icon = $(this).find('i');

can do the trick可以解决问题

"li").click(function() {
   var colorClass = this.className;
   console.lo

Try to do just like this.尝试这样做。

Can you post your Html where the icon located?你能把你的 Html 贴在图标所在的位置吗?

Basically, you can locate the icon with $(this).closest( ".opener i" )基本上,您可以使用$(this).closest( ".opener i" )找到图标

$(this).closest('.parentElemnt').find('.opener i')

But to give you the exact code I need to see the HTML code.但是为了给你确切的代码,我需要查看 HTML 代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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