简体   繁体   English

jQuery中的addClass不添加类

[英]addClass in jQuery is not adding a class

I have been searching for an answer for this question but still, my problem exists. 我一直在寻找这个问题的答案,但仍然存在我的问题。 I tried all the answers from here (StackOverflow) and from other websites but it still didn't solved my problem. 我从这里(StackOverflow)和其他网站尝试了所有答案,但仍然不能解决我的问题。

Additional Information: There's no error on DevTools. 附加信息:DevTools上没有错误。

HTML: HTML:

 <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="styles.css"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <title>Test</title> </head> <body> <div class="nav"> <div class="container"> <ul> <li><a href="#">About</a></li> <li><a href="#">Work</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> <script src="sample.js"></script> </body> </html> 

CSS: CSS:

 /*Nav Styles*/ .nav li { text-transform: uppercase; list-style-type: none; display: inline; } .nav a { text-decoration: none; color: black; } /*Active Menu*/ .activeMenu { color: red; } 

JS: JS:

 var x = function(){ $('.nav li').click(function(){ //alert($(this).text()); <-- It's working $(this).addClass('activeMenu'); return false; }); }; $(document).ready(x); 

Thanks a lot! 非常感谢!

The issue is because your CSS rule for .activeMenu is not specific enough to override the colour set on the a element. 问题是因为您的.activeMenu CSS规则不够具体,无法覆盖在a元素上设置的颜色。 You need to make the rule more specific: 您需要使规则更具体:

.activeMenu a {
    color: red;
}

Or set !important on it. 或在其上设置!important The former is better practice. 前者是更好的做法。

Example fiddle 小提琴的例子

You must change your css too: 您也必须更改CSS:

.activeMenu a { color: red; .activeMenu a {颜色:红色; } }

 var x = function(){ $('.nav li').click(function(){ //alert($(this).text()); <-- It's working $(this).addClass('activeMenu'); return false; }); }; $(document).ready(function() { x(); }); 
 .nav li { text-transform: uppercase; list-style-type: none; display: inline; } .nav a { text-decoration: none; color: black; } /*Active Menu*/ .activeMenu a { color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="nav"> <div class="container"> <ul> <li><a href="#">About</a></li> <li><a href="#">Work</a></li> <li><a href="#">Contact</a></li> </ul> </div> </div> 

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

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