简体   繁体   English

清除#而不重新加载页面

[英]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: 我将所有网站的页面加载到主索引页面中,并通过将href分成多个段并使用.hash函数在主域名之后添加这些段来更新URL显示,如下所示:

$('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/并单击“关于”链接时,将加载所选页面,并显示地址栏:

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

But if a user starts with a different page: 但是,如果用户以其他页面开头:

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

Then after the click, the url becomes: 然后,单击后,URL变为:

http://www.mywebsite.com/#/about/#/about 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(/#.*/,'') 尝试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. 因为href将包含完整的路径,包括哈希。

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. 清空它(保留# )(如果您还从href中删除# ,则您的页面将始终重新加载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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