jquery - 如果使用 "!important",如何使用 removeClass()?

标签 jquery html css

为了覆盖我无法更改的 CSS,我需要在出现文本“Turkey | Meats”时使用“!important”规则将类“hide”添加到第一个 li。

现在,当我尝试使用 .removeClass() 删除“隐藏”类时,“隐藏”仍然存在,我认为这是因为“!important”规则。这是我的编码:

(function($) {
  if ($(".nav li:nth-of-type(2)").text().trim() == "Turkey | Meats") {
    $(".nav li:nth-of-type(1)").addClass("hide");
  } else {
    $(".nav li:nth-of-type(1)").removeClass("hide");
  }
});
.hide {
  display:none !important;
}
<div class="nav">
  <ul class="nav-list">
    <li class="nav-link">
      <a href="">Fish</a>
    </li>
    <li class="nav-link">
      <a href="">Turkey | Meats</a>
    </li>
  </ul>
</div>

最佳答案

添加/删除类工作正常,检查这个例子:

if ($(".nav li:nth-of-type(2)").text().trim() == "Turkey | Meats") {
        $(".nav li:nth-of-type(1)").addClass("hide");
        console.log("Fish class: "+$(".nav li:nth-of-type(1)").attr("class"))
} else {
        $(".nav li:nth-of-type(1)").removeClass("hide");
        console.log("Fish class: "+$(".nav li:nth-of-type(1)").attr("class"))
}
$("button:first").click(function(){
    $(".nav li:nth-of-type(1)").removeClass("hide");
    console.log("Fish class: "+$(".nav li:nth-of-type(1)").attr("class"))
});
$("button:last").click(function(){
    $(".nav li:nth-of-type(1)").addClass("hide");
    console.log("Fish class: "+$(".nav li:nth-of-type(1)").attr("class"))
});
.hide {
  display:none !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="nav">
  <ul class="nav-list">
    <li class="nav-link">
      <a href="">Fish</a>
    </li>
    <li class="nav-link">
      <a href="">Turkey | Meats</a>
    </li>
  </ul>
  <button type="button">Remove Class .hide</button>
  <button type="button">Add Class .hide</button>
</div>

关于jquery - 如果使用 "!important",如何使用 removeClass()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46370895/

相关文章:

javascript - HTML/Javascript - 360 度图片的路径更改(以显示不同的变化)

javascript - 在点击事件中分配点击事件处理程序

javascript - 从下拉列表中选择 javascript 事件

css - 使用 Twitter-bootstrap 形式布局

html - 尝试在具有不对称边(倾斜矩形)的 div 中写入文本,但它在 2 行之间拉伸(stretch),为什么?

jquery - js : change style based in scroll position

jquery - 当 tbody css 显示属性为 block 时,如何对齐 thead 和 tbody 中的列

html - div 移动下面的其他 div

html - 如何获取自动播放YouTube视频的嵌入式代码

javascript - 不可选择的文本(链接)