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

旧时模样 提交于 2019-12-05 21:41:49

You need to use hashchange event:

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();
};

Also when you are using hashchange event, there is no 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>

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

Check DEMO here.


First Time

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

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

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

Check the HTML5 history API. It allows you to work with the browser history

HTML5 history api

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

or window.onhashchange event if you don't want to use jQuery

If you're going to be using AJAX, you'll really want to look into using jQuery instead of raw javascript unless your intention is educational. jQuery is just a mainstay of the web now.

If you must use those hashes...

Use jQuery Special Events, and use the hashchange event:

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

Script:

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

However, for your scenario...

You don't need to use those # values at all as you're passing the values in your function arguments anyway according to the code you provided, just do this:

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

Alternatively (and preferably, as you're using AJAX according to the tags) you can use jQuery and its builtin selector click events which use Event Listeners:

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

Script is this easy:

$('.divLink').click(function(){
    $('#box').html("This is "+$(this).id());
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!