简体   繁体   中英

Clear the # without reloading the page

I am loading all website's pages into the main index page, and updating URL display by splitting the href into segments and adding the segments after the main domain name with .hash function, like this:

$('a').click(function(event) {
event.preventDefault();
var my_url = this.href;

var pathArray = this.href.split('/');

var newPathname = "";
for ( i = 3; i < pathArray.length; i++ ) {
  newPathname += "/";
  newPathname += pathArray[i];
}

$('body').load(my_url);
window.location.hash = newPathname;

This works okay, but I'm facing a little problem. When a user accesses http://www.mywebsite.com/ and then clicks, for example, on "About" link, the selected page loads, and the address bar displays:

http://www.mywebsite.com/#/about

But if a user starts with a different page:

http://www.mywebsite.com/#/about

Then after the click, the url becomes:

http://www.mywebsite.com/#/about/#/about

and so on, to infinity.

How can this be solved?

Perhaps there's a way to clear the hash and then display the new hash (that is, remove everything that starts with #/ and then add the new hash) – or maybe there's a better solution?

Try var my_url = this.href.replace(/#.*/,'')
This will remove the # and anything after it.

If you want to split just the path component of the current URL, then don't use

var pathArray = this.href.split('/');

because href will contain the full path including the hash.

Use

var pathArray = this.pathname.split('/');

instead.

Changing the hash doesn't refresh your page. At most it forces the browser to scroll top. If you want you can do:

window.location.hash = ""; 

to empty it (retaining the # ) if you also remove the # from the href then your page will always reload.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM