javascript 在 jQuery addClass 中使用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30386958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:07:10  来源:igfitidea点击:

Using a variable with jQuery addClass

javascriptjqueryhtmlcss

提问by antfuentes87

Trying to mix a variable with :not then use that variable with addClass. but no luck yet.

尝试将变量与 :not 混合使用,然后将该变量与 addClass 一起使用。但还没有运气。

HTML

HTML

<ul>
  <li><a href="#">Nav One</a></li>
  <li><a href="#">Nav Two</a></li>
  <li><a href="#">Nav Three</a></li>
  <li><a href="#">Nav Four</a></li>
</ul>

LESS

较少的

ul{
    li{
        a{
            color: black;
            transition: all 0.5s ease;
            font-size: 3rem;
            text-decoration: none;
        }
    }
}
.enc-non-active{
    color: gray;
}

JAVASCRIPT

爪哇脚本

myFunction('ul li a', 'enc-active', 'enc-non-active');

function myFunction($menu, $activeClass, $nonActiveClass) {
   $(function(){
        $($menu).hover(function(){
            $(this).addClass($activeClass);
        },
        function(){
            $(this).removeClass($activeClass);
        });
        $($menu).hover(function(){
            var fullPath = $menu + ':not(' + $activeClass + ')';
            $(fullPath).addClass($nonActiveClass);
        },
        function(){
            var fullPath = $menu + ':not(' + $activeClass + ')';
            $(fullPath).removeClass($nonActiveClass);
        });
    });
}

Here is the CodePen http://codepen.io/antfuentes87/pen/pJEaebif anyone can let me know what I am doing wrong, that would be great. Thanks for your time.

这是 CodePen http://codepen.io/antfuentes87/pen/pJEaeb如果有人能让我知道我做错了什么,那就太好了。谢谢你的时间。

采纳答案by Yang Li

You forgot a dot in :not(. - easily fixed http://codepen.io/anon/pen/zGKRyW

你忘记了 :not(. - 很容易修复http://codepen.io/anon/pen/zGKRyW

var fullPath = $menu + ':not(.' + $activeClass + ')';
$(fullPath).addClass($nonActiveClass);

回答by charlietfl

You are missing a dot to make the class name into a css selector

您缺少一个点来将类名变成 css 选择器

Change

改变

var fullPath = $menu + ':not(' + $activeClass + ')';

To

var fullPath = $menu + ':not(.' + $activeClass + ')';

DEMO

DEMO