简体   繁体   English

jQuery addClass不起作用,但是css可以

[英]jQuery addClass doesn't work, but css does

Does Not Work 不起作用

CSS CSS

.active 
{
    display: block;
}

JS JS

$("#li_1 ul").addClass('active');

Does Work 工作

JS JS

$("#li_1 ul").css('display', 'block');

Which leads to me my question, why does the css function work and not the addClass? 这导致了我的问题,为什么css函数工作而不是addClass? There's no difference between the selectors at all. 选择器之间没有区别。

Additional info - 附加信息 -

  • Using jQuery version 1.6.4 使用jQuery版本1.6.4
  • JS in question here resides in a .js file being included in an ASP.NET masterpage 这里讨论的JS驻留在ASP.NET主页中包含的.js文件中
  • masterpage has link to stylesheet containing the CSS in question here (ie - the 'active' style is available to the masterpage) masterpage链接到包含相关CSS的样式表(即 - 主页的“活动”样式可用)

What about using this statement: 使用此声明怎么样:

.active {
  display:block !important;
}

I think something overrides your .active rule in your CSS stylesheet. 我认为有些东西会覆盖CSS样式表中的.active规则。

More informations about CSS priorities right here . 关于CSS优先级的更多信息就在这里

Without seeing your HTML it's hard to say for sure why it's not working. 没有看到你的HTML,很难肯定为什么它不起作用。 I can say that the JS you've posted should work fine. 我可以说你发布的JS应该可以正常工作。 I have a working example here: 我在这里有一个工作的例子:

http://jsfiddle.net/hsyEw/1/ http://jsfiddle.net/hsyEw/1/

One thing that jumps out is that this selector $("#li_1 ul") looks a little weird. 跳出来的一件事是这个选择器$("#li_1 ul")看起来$("#li_1 ul") do you really have a ul element that is a child of an element with an id that implies it is an li ? 你真的有一个ul元素是一个元素的子元素,其id值暗示它是一个li

Your second JS example is applying style directly to the element which will overwrite any CSS Class styles that are being applied, so if you have some other CSS present that is affecting that element this could explain the behavior you are seeing. 你的第二个JS示例是直接将样式应用于将覆盖正在应用的任何CSS类样式的元素,因此如果你有一些影响该元素的其他CSS,这可以解释你所看到的行为。

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

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