我需要使用URL中的锚点(#)更新我的页面

I need to update my page using Anchor (#) in URL

本文关键字:更新 我的 URL      更新时间:2023-09-26

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>

输出

Home
Profile
Message
Setting


这是主页

正如代码所说,当我单击任何link时,我的Div内容都会更新,但问题是当用户goes back单击Back Button of Browser时,我Div的内容不会更改
我希望用户Goes BackGoes Forward或他直接将路径放在address barwww.*****/index.php#profile中,我的Div的内容应该更改。

注意
我使用document.location.hash来获得hash的值,如下所示:

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

但它只在用户goes backrefresh the page 时工作

Plz帮助我如何实现这一点:(

您需要使用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属性(,并且CCD_ 23事件被激发。

点击此处查看演示。


第一次

当用户第一次带着哈希来到你的页面时:

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

我们必须显示所需的页面(此处为message(,因此我们必须运行hash_changed()函数我们第一时间声明。为此,我们必须等待DOM就绪或window.onload

查看HTML5历史API。它允许您使用浏览器历史

HTML5历史api

$(window).on('hashchange', function() {
     alert(location.hash);
});

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

如果你要使用AJAX,你会非常想使用jQuery而不是原始javascript,除非你的意图是教育性的。jQuery现在只是web的支柱。

如果必须使用这些哈希

使用jQuery特殊事件,并使用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及其内置的选择器点击事件,这些事件使用事件监听器:

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

脚本就是这么简单:

$('.divLink').click(function(){
    $('#box').html("This is "+$(this).id());
}