簡體   English   中英

li標記的點擊功能不適用於除#以外的href

[英]Click function of li tag not working with href other than #

這是我的導航菜單:

<ul id="nav">
          <li><a href="index.html">Home</a></li>
          <li><a href="gallery.html">Gallery</a></li>
          <li><a href="#">Recipies</a></li>
          <li><a href="#">Contact</a></li>
</ul>


單擊li時,出現了一片綠葉,jQuery代碼實現了這一點:

$(document).ready(function(){

    $( "#nav li" ).click(function(event) {
    event.preventDefault();
    $(this).addClass('greenLeaf').siblings('li').removeClass('greenLeaf');

});
});


現在的問題是,當我使用#-而不是“ index.html”時,就像魅力一樣,如果插入了鏈接,則需要使用event.preventDefault,這也將阻止瀏覽器跟隨該鏈接-這顯然不是我所追求的。 有什么方法可以解決這個問題? 我敢肯定這是一個簡單的解決方法,但我無法弄清楚...

然后,您需要一個CSS規則:

#nav li a:visited{
  /* Add greenLeaf class code here */
}

如注釋中所述,您想在:visited選擇器內使用用於.greenLeaf的CSS。

據我了解,您正在嘗試在菜單中標記當前頁面

所以它是這樣的:

$(document).ready(function(){
    $( "#nav a" ).each(function(){
     if ($(this).attr("href") == window.location.pathname){
      $(this).addClass("greenLeaf");
     }
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM