2017-09-22 85 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>

相關問題