2011-02-09 55 views
2

當用戶來自Google或爲其添加書籤時,我製作了單頁佈局網站,其中菜單不顯示活動/當前鏈接。將課程添加到適合url的孩子

我已經制作了一個正常工作的腳本,但正如你所看到的那樣....它看起來非常可怕。我該如何做到這一點聰明?

//Set .active to current page link 
    if (location.href.indexOf("#2") != -1) { 
     $("#menu li:nth-child(1) a ").addClass("active"); 
    } 
    if (location.href.indexOf("#3") != -1) { 
     $("#menu li:nth-child(2) a ").addClass("active"); 
    } 
    if (location.href.indexOf("#4") != -1) { 
     $("#menu li:nth-child(3) a ").addClass("active"); 
    } 
    if (location.href.indexOf("#5") != -1) { 
     $("#menu li:nth-child(4) a ").addClass("active"); 
    } 
    if (location.href.indexOf("#6") != -1) { 
     $("#menu li:nth-child(5) a ").addClass("active"); 
    } 

預先感謝您...

回答

3

如何像:

$("#menu li:nth-child(" + (location.hash.slice(1) - 1) + ") a ").addClass("active"); 
+0

它不會超過10個菜單項 – kirilloid 2011-02-09 22:14:34

1
var m = location.href.match(/#(\d+)/); 
if (m) { 
    var index = parseInt(m[1]) - 1; 
    if (index >= 1) 
    $("#menu li:nth-child("+index+") a ").addClass("active"); 
}