记住上次打开状态

时间:2009-03-27 18:43:16

标签: jquery

在网站http://www.ryancoughlin.com/hp/?c=posters上,我在左侧使用此代码:

$(".menu-header").click(function() {
        $(this).next().toggle('slow');
        return false;
}).next().hide();

如果您打开其中一个并点击另一个部分,它会关闭,有没有办法让该状态保持打开状态?

2 个答案:

答案 0 :(得分:4)

您的部分保持开放状态正常,但在您打开页面时会关闭它们。

然而,您的问题并未消除这两个问题之间的歧义。

您可能希望如何使其在这些页面上起作用是注入一个变量来计算出您所在的页面。

   jQuery(function($){ 
     var matches;
     if( matches = (new String(document.location)).match(/\?c=\w+/) ) {  
        $("a[href=" + matches[0] + "]").parents("ul").toggle(); 
     }
   });

虽然可以作为一种短期解决方案。

所以完整的代码将是(注释的)

/* Document Ready, $ = jQuery inside this scope regardless  */

jQuery(function($){  

  /* Bind the click event on all the menus, then hide them all. */

  $(".menu-header").click(function() {
            $(this).next().toggle('slow');
            return false;
  }).next().hide();
  /*
   * Check to see if we're already on a sub-menu-item
   * By looking in the current pages url for the string '?c=somewordhere'
   */
  var matches;
  if( matches = (new String(document.location)).match(/\?c=\w+/) ) {  
    /*
     * If we are, search the page for a link to that submenu item
     * ( by looking for the '?c=somewordhere' part in the hrefs ) 
     * and find its parent menu `ul` and show it.
     */
    $("a[href=" + matches[0] + "]").parents("ul").toggle(); 
  }

}); # End Document Ready Scoping. 

为清楚起见,

jQuery(function($){ 

}); 

是一个非常方便的速记符号,非常强大。这相当于做

jQuery(document).ready(function($){ 

});

反过来几乎相当于做

jQuery(document).ready(function(){ 
     var $ = jQuery; 
});

以故障安全方式保证“$”将成为此函数中的jQuery,无论页面上的其他内容如何。

答案 1 :(得分:0)

我建议使用reallysimplehistory。它允许您透明地在页面调用之间保存状态(不需要乱用cookie,URL等)。

你也可以在你的网站上使用Ajax,但是如果你想让后退按钮工作,你还是会使用像RSH这样的东西。 =]

相关问题