从URL传递值

时间:2010-11-24 00:01:17

标签: jquery css

你好,我有一个网站,我显示/隐藏默认情况下在开始时加载的分区。但问题是,当我刷新页面时,它总是会回到主要部门。有什么办法我可以做一些像mysite / #news mysite /#about?

我的代码:

        $('a#btnNews').click(function()
        {
            $('#divabout').hide();
            $('#divnews').fadeIn();
            $('#pagetimer').load('scripts/loadtimer.php');
            return false;
        });

        $('a#btnAbout').click(function()
        {
            $('#divrooster').hide();
            $('#divabout').fadeIn();
            $('#pagetimer').load('scripts/loadtimer.php');
            return false;
        });

2 个答案:

答案 0 :(得分:0)

在此期间,您可以使用window.location.hash代替。

if (location.hash != "") {
  $('a#'+location.hash).click();
}
$('a#btnNews').click(function()
{
  $('#divabout').hide();
  location.hash = 'btnNews';
  $('#divnews').fadeIn();
  $('#pagetimer').load('scripts/loadtimer.php');
  return false;
});
$('a#btnAbout').click(function()
{
  $('#divrooster').hide();
  location.hash = 'btnAbout';
  $('#divabout').fadeIn();
  $('#pagetimer').load('scripts/loadtimer.php');
  return false;
});

确保将所有这些内容放在$(function(){});$(document).ready(function(){});

您可以使用$('a#'+location.hash).click();,也可以直接更改目标div中的哈希值。

您也可以使用e.preventDefault()代替return false;。 (它也更好)例如。

$('a#btnNews').click(function(e) {
e.preventDefault();
...
});

答案 1 :(得分:0)

与您不一样,但您可以通过更新哈希来保存页面状态。

有适合​​您的高级插件,或者您可以自己动手。

插件: http://benalman.com/projects/jquery-bbq-plugin/

自己动手: http://jsbin.com/oyeqe3/3#List2

在你自己的例子中你可以看到#List2作为哈希传递。它将保持显示的第二个列表和其他隐藏的列表。

上面链接中的代码示例:

HTML:

<a href="#List1" class="trigger">Show 1</a> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
<a href="#List2" class="trigger">Show 2</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;
<a href="#List3" class="trigger">Show 3</a> &nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp; 

<ul id="List1">
    <li>One</li>
</ul>
<ul id="List2">
    <li>Two</li>
</ul>
<ul id="List3">
    <li>Three</li>
</ul>  

的jQuery

// when the trigger is clicked
$('a.trigger').click(function(){

  // hide all lists
  $('ul').hide();

  // show the correct ul (based on the hash of the clicked link)
  $('ul'+this.hash).show();

  // update the hash
  window.location.hash = this.hash;

});

// when the page loads and there is a hash
if( window.location.hash ){

  // could do a bunch of different things here, we'll click the link w/ the corresponding hash
  $('a.trigger[href='+window.location.hash+']').trigger('click');

};

不是一个漂亮的实现,但你希望得到这个想法。