2017-09-22 140 views
0

为了覆盖我无法更改的CSS,当文本“Turkey | Meats”存在时,我需要用“!important”规则向第一个li添加类“hide”。如果使用“!important”,如何使用removeClass()?

现在,当我尝试用.removeClass()去除“hide”类时,“hide”仍然存在,我认为这是因为“!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>

+0

的[我可以使用jQuery到可能的复制删除/否定css!重要规则?](https://stackoverflow.com/questions/11890739/can-i-use-jquery-to-remove-negate -css-important-rule) – Scath

+1

你检查了元素吗?这个班真的被删除了吗? – jack

+0

尝试console.log该元素。 !重要的不会影响类的移除...... –

回答

0

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

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>