3

index.php

<html>
 <head>
  <title>My Title</title>
  <script type="text/javascript">
   function getLink(data) {
    document.getElementById("box").innerHTML="This is "+data;
   }
  </script>
 </head>
 <body>
  <a href="#home" onClick="getLink('Home')">Home</a><br />
  <a href="#profile" onClick="getLink('Profile')">Profile</a><br />
  <a href="#message" onClick="getLink('Message')">Message</a><br />
  <a href="#setting" onClick="getLink('Setting')">Setting</a><br />
  <hr />
  <div id="box"></div>
 </body>
</html>

Output

Home
Profile
Message
Setting


This is Home

As the code says my Div contents updated when i click any of the link but the problem is that when user goes back by clicking Back Button of Browser the content of my Div donot changes.
I want that either user Goes Back, Goes Forward or he directly puts the path in the address bar www.*****/index.php#profile the content of my Div should be change.

Note
I used document.location.hash to get the value of hash like this :

<head>
 <script>
  var hashValue=document.location.hash;
  alert(hashValue);
 </script>
</head>

but it works only when user goes back and then refresh the page

Plz help me how can i achieve this :(

4

4 回答 4

2

您需要使用hashchange事件:

function hash_changed() {
    var data = document.location.hash.substr(1);
    var box = document.getElementById("box");

    if (data) {
        // inner page
        box.innerHTML="This is " + data;
    }
    else {
        // homepage
        box.innerHTML = "";
    }
}

window.onhashchange = function () {
    hash_changed();
};

window.onload = function () {
    hash_changed();
};

此外,当您使用hashchange事件时,无需onclick为您的链接设置:

<a href="#home">Home</a>
<a href="#profile">Profile</a>
<a href="#message">Message</a>
<a href="#setting">Setting</a>

当用户单击链接时,哈希值会自动更改(带有href链接属性),并且hashchange会触发事件。

在此处查看演示


第一次

当用户第一次使用哈希访问您的页面时:

http://fiddle.jshell.net/B8C8s/9/show/#message

我们必须显示想要的页面(message这里),所以我们必须hash_changed()第一次运行我们在上面声明的函数。为此,我们必须等待 DOM 准备好或window.onload.

于 2013-06-03T11:56:03.727 回答
0

检查 HTML5 历史 API。它允许您使用浏览器历史记录

HTML5 历史 API

于 2013-06-03T11:54:07.370 回答
0
$(window).on('hashchange', function() {
     alert(location.hash);
});

或者 window.onhashchange 事件,如果你不想使用 jQuery

于 2013-06-03T11:54:35.950 回答
0

如果您打算使用 AJAX,除非您的意图是教育性的,否则您真的很想研究使用jQuery而不是原始 javascript。jQuery 现在只是 Web 的中流砥柱。

如果您必须使用这些哈希...

使用jQuery Special Events,并使用hashchange事件:

<a href='#home'>Home</a>

脚本:

$(window).on('hashchange', function() {
    $('#box').html("This is "+event.fragment);
});

但是,对于您的情况...

您根本不需要使用这些#值,因为您正在根据您提供的代码传递函数参数中的值,只需执行以下操作:

<a href="" onClick="getLink('Home');return false;">Home</a><br />

或者(最好,当您根据标签使用 AJAX 时)您可以使用 jQuery 及其使用Event Listeners的内置选择器点击事件:

<a href='javascript:void();' class='divLink' id='home'>Home</a><br/>

脚本很简单:

$('.divLink').click(function(){
    $('#box').html("This is "+$(this).id());
}
于 2013-06-03T11:54:57.983 回答