开发者

Ajax navigation without hash in link inside anchor tag

开发者 https://www.devze.com 2023-04-05 01:40 出处:网络
I normally use ajax nav开发者_Python百科igation by using # in <a> in some links like <a href=\"#page2\">Page 2</a> which changes the url to www.example.com/#page2

I normally use ajax nav开发者_Python百科igation by using # in <a> in some links like <a href="#page2">Page 2</a> which changes the url to www.example.com/#page2

well i found a way to remove the # and change it to www.example.com/page2 by using history.pushState() but how to remove the # from the anchor tag and still make the ajax work properly. i.e i want to make the <a href="page2">Page 2</a>

this is how facebook has implemented ajax i guess..


pushState() is a new feature to browsers that lets you change the url without changing the url. For older browsers, you stil need to use the hash /#/page or /#!/page (twitter) or /#page

If you want your urls to look like that you have a few options.

You could prevent the link from happening with something like:

$('a').click(function(e) {
   history.pushState(...);
   e.preventDefault(); // stops the link from happening
});

Or just use Regex to strip the # out of the link HREF and update the pushstate with that..

To use the new feature with hash fallback, you should take a look into history.js

http://plugins.jquery.com/project/history-js

Good luck!


An A element with an HREF attribute is a link and is intended for navigating elsewhere. An A element with a NAME attribute is an anchor and is intended to be the destination of a link. If it has both attributes, it is an anchor and a link.

If you are using an element to change page content (whether you use AJAX or any other method is irrelevant) then you don't need an A element at all, you can use any element with an onclick listener and just change the content. No issue with changing URLs. If you want it to look like a link, then use CSS to style a span to look like a link (or whatever).

Users expect links (and things that look like links) to take them to another page. They expect things that look like buttons to do pretty much anything, including navigating elsewhere, so your "links" probably should look like buttons.

If you insist on using an A element, then use a real URL in the href and have the onclick listener that does the AJAX (or page modification) return false. That way the link won't be followed and the URL won't change in the address bar.

Of course I may have misunderstood what you mean by "AJAX navigation", which is an ambiguous term to me.

0

精彩评论

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