开发者

Rewrite url in browser's address bar with #?

开发者 https://www.devze.com 2023-01-06 07:58 出处:网络
I have some elements on my page that get loaded via an ajax call. I\'d like to make the url in the user\'s browser change when they click an item. For example, my page has a list of animals:

I have some elements on my page that get loaded via an ajax call. I'd like to make the url in the user's browser change when they click an item. For example, my page has a list of animals:

Horse
Cow
Pig

when the user clicks one of those items, I want to update the url in their browser's address bar (not reload the page):

http://www.mysite.com#Hors开发者_如何学运维e
http://www.mysite.com#Cow
http://www.mysite.com#Pig

I think that's allowed, putting the # symbol in the address without reloading the page. Is there a way to do this in jquery?

Thanks


You can do it in vanilla JS, no need for jQuery using location.hash, like this:

window.location.hash = "Cow";


Can't you have the element linked to the hash?

<a href="#Pig">Pig</a>


Be warned! window.location.hash is not implemented in every browser! A fix for this would look like:

if (!("hash" in window.location)) {
  window.location.__defineGetter__("hash", function() {
    if (location.href.indexOf("#") == -1) return "";
    return location.href.substring(location.href.indexOf("#"));
  });
  window.location.__defineSetter__("hash", function(v) {
    if (location.href.indexOf("#") == -1)
      location.href += v;
    location.href = location.href.substring(0, location.href.indexOf("#")) + v;
  });
}

This is untested, so test it first! My advice would be to use:

<a href="#Pig">Oink!</a>

to change urls. (By the way, the behavior of window.location.hash that is implemented here is the same you expect with browsers that implement it. You have to add the hash character to the url.)


I'd look into using SWFAddress for deep-linking .... it works the same in JavaScript as ActionScript

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号