2010-12-11 208 views
0

我有一個水平菜單導航的頁面標題,如AB C. A有子菜單D,E和B有子菜單F和G.默認情況下,標題F和G是當我點擊B時,F和G應該是可見的,而D和E應該是隱藏的。我創建了一個小函數,當它們各自的菜單被點擊時,它們設置子菜單的顯示屬性,這可以工作,但是當頁面加載時,我回到了第一個,這意味着D和E被顯示,並且F和G被隱藏。使用Javascript隱藏和顯示元素

如何解決這個使用JavaScript?我對js非常陌生,所以不用jQuery來思考。

回答

1

如果可能,你可以添加一個散列#到新的URL。尋找那些通過JavaScript顯示的基地。

僞代碼:Example Here - Source to example here

var hash = location.hash 
if(hash == '#menuA' || hash == '') { 
    //show menuA 
} else if(hash == '#menuB') { 
    // show B 
.....etc 
+0

謝謝感謝您的幫助。 – 2010-12-11 03:51:08

+0

沒問題的人,祝你學習好! – subhaze 2010-12-11 04:02:35

1

您可以設置一個cookie,其中包含選擇哪個菜單的信息,然後讀取cookie並在頁面加載時適當地設置菜單。你可以在這裏找到一些不錯的餅乾功能:http://www.quirksmode.org/js/cookies.html

+0

非常感謝您的幫助。 – 2010-12-11 03:52:42

1

對不起,我只知道jQuery的不夠好,來完成我想你想的副手。 也許僞代碼會有所幫助。如果您發佈用於製作子菜單的HTML,它可能會有所幫助。

此示例只是將nav元素與頁面上的對象相關聯。

SCRIPT(優選在所有頁面鏈接到外部.js文件):

//after you've set all sub-menus to display:none 

//for each nav element 
$('#nav a').each(function(){ //just like a for loop 
    var a,b; 
    // set a equal to the contents of the current nav element in the loop 
    a =$(this).html(); 
    //set b equal to the contents of the first <h2> element on the current page 
    //or to whatever you want to use to distinguish as "a match" (needs not be visible) 
    b =$('h2:first').html(); 
    //if the match is made... in this case, an exact match 
    if(a == b){ 
      //Here you would have your display children code 
      //or display D and E or F and G code, depending on how you've set it up    
     }else //code to execute if no match is made 
    }); 

我摸不着頭腦的團隊項目...我有很多東西要學了。喜歡它

+0

謝謝吉姆,感謝您的幫助。 – 2010-12-11 03:52:17

0

這實際上很簡單,通過jQuery。我嘲笑一個非常基本的菜單,無序列表和列表項here

我知道你提到你對JavaScript非常陌生,我當然明白,但熟悉像jQuery這樣的框架是絕對必要的。 jQuery中的選擇器功能非常強大。

+0

感謝您的幫助。我一定會開始熟悉jquery。 – 2010-12-11 16:43:36