我在JQuery中很新,我對addClass()有個疑問。我花了一些時間來嘗試這個工作,但似乎我做錯了什麼。我用HTML和bootstrap創建了一個頂級菜單。我假設訪客首先登陸我的index.php,因此我爲index.php創建了class =「active」。然後,如果他們點擊頂部菜單上的任何其他鏈接(例如關於我們),那麼class =「active」將添加到index.php的「li」選項卡中並從中刪除class =「active」。jQuery中的addClass
下面是我的HTML代碼:
<div class="nav-collapse collapse">
<ul class="nav pull-right">
<li id="home" class="active"><a href="index.php"> Home</a></li>
<li id="about"><a href="about_us.php"> About Us</a></li>
<li id="browse"><a href="browse.php"> Browse</a></li>
<li id="contact"><a href="contact.php"> Contact</a></li>
</ul>
</div>
及以下,我使用,並嘗試完成這件事的jQuery代碼。
$(function(){
var sidebar = $('.nav');
sidebar.delegate("li", "click", function(){
if($(this).hasClass('active')){
//If click on the tab that is currently active, it will do nothing.
}else{
sidebar.find('.active').addClass('inactive');
sidebar.find('.active').removeClass('active');
$(this).removeClass('inactive');
$(this).addClass('active');
}
});
});
我在本地服務器上測試了它。點擊後,我可以看到頂部菜單中的選項卡變成灰色,但沒有保留。所以我確信我做錯了什麼,但不知道在哪裏。我在JQuery中真的很新,所以我希望我能向你們學習。謝謝!
我的猜測是,沒有必要使用第二類的非活動狀態。 – isherwood