为什么 addClass 在此代码中不起作用
在下面的函数代码中,当我使用 CSS 时,它工作正常。当我将此 CSS 添加到类中时它不起作用
function setTab(selection) {
$("#"+selection).css('background', '#CC0000');
$("#"+selection).css('color', '#ffffff');
// Both the Above statements works fine
$("#"+selection).addClass("selectedclass");//doesnot work
}
.selectedclass li{
background: #CC0000;
color: #ffffff;
}
In the below Code of my function when i use CSS it works fine. when I add this CSS to a class it is not working
function setTab(selection) {
$("#"+selection).css('background', '#CC0000');
$("#"+selection).css('color', '#ffffff');
// Both the Above statements works fine
$("#"+selection).addClass("selectedclass");//doesnot work
}
.selectedclass li{
background: #CC0000;
color: #ffffff;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我敢打赌,这个班级正在被另一种风格所统治。在本例中这是最明显的。前两行代码起作用的原因是因为它们直接编辑样式,在添加类的情况下,级联规则仍然适用
尝试这些:
您的代码很简单,所以它可能是正确的。但你可以像这样清理它:
What I bet is happening is that the class is being overruled by another style. Which is the the most obvious in this case. The reason the first two lines of code work is becaue they edit the style directly, where adding a class, the cascading rules still would apply
Try these:
Your code is simple, so it's probably correct. But you could clean it up a bit like so:
是否有可能存在比所应用的类选择器更具体的选择器?您是否查看过 Firebug 中的元素以了解该元素从何处获取其属性?使用前两个语句,您可以直接在元素上设置样式,这将优先。使用第二个,它将取决于您定义的各种样式、它们的顺序和特殊性。也可能是您的类应用于错误的元素,即直接应用于
li
而不是父级ul
(ol
)。在这种情况下,您需要将规则更改为li.selectedClass
。另外,您知道可以将 jQuery 函数链接在一起吗?
css
有一个重载,它采用键/值对的映射。Is it possible that there is a more specific selector than the class selector being applied? Have you looked at the element in Firebug to see where the element is getting its properties? Using the first two statements, you're setting the style directly on the element, which will take precedence. Using the second, it will depend on the various styles that you have defined, their order and specificity. Could also be that your class is applied to the wrong element, i.e., directly to the
li
instead of the parentul
(ol
). In that case you need to change your rule toli.selectedClass
.Also, did you know that you can chain the jQuery functions together? And
css
has an overload that takes a map of key/value pairs.