本文介绍了我需要更新URL使用锚(#)我的网页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的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


This is Home

由于code说我的事业部内容更新,当我点击任何的链接但问题是,当用户返回点击返回浏览器的按钮我的事业部 DONOT变化。
我想,无论是用户返回前进或者他直接把路径在地址栏 WWW。***** / index.php文件#简介我的事业部应该改变。

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.

注意
我用 document.location.hash 获得的散列值所示:

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>

但它的工作原理,只有当用户返回然后刷新页面

PLZ帮我,我怎么能做到这一点:(

Plz help me how can i achieve this :(

推荐答案

您需要使用 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 为您的链接:

Also when you are using hashchange event, there isno need to set onclick for your links:

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

在一个链接用户点击,散列自动改变(与的href 链接的属性),和 hashchange 事件被解雇。

When user click on a link, the hash automatically changes (with href attribute of link),and hashchange event get fired.

检查演示这里。

当用户来到你的页面首次与哈希:

When a user come to your page for the first time with a hash:

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

我们必须表现出想要的页面(的消息这里),所以我们必须运行 hash_changed()功能我们声明以上,在第一次。对于这一点,我们必须等待DOM准备或的window.onload

We must show the wanted page (message here), so we must run hash_changed() functionwe declare above, at first time. For this, we must wait for DOM ready or window.onload.

这篇关于我需要更新URL使用锚(#)我的网页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:59