2010-12-11 172 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