Trigger onClick() event with direct links
I have a website with a navigation bar. When a link is clicked, it uses the onClick()
handler开发者_JS百科 to change the content of a page.
For example. If the about us link is clicked, the page content will change to the about us content, and the URL will become xxxxx.com/#about
. However, when linked directly to xxxxx.com/#about
it opens the default index.php
page.
How do I directly link to the pages, as if it was onClick()
?
You can call the function used in onclick on page load.
window.location.hash
will give you #about in your example, so you can load(or show) the relevant content.
You need get the #something
on page load, and then if it is found, call your onclick
function with it.
tag = /#[^\s]+/.exec(document.location.href);
tag = tag.substring(1);
// you have what you want
so you're loading in content with Ajax?
A quick and dirty way to do this would be to look at the url
document.location.href
You can get the action you're looking for like this
// get the url and split it at the "#" character into an array
var urlSplit = document.location.href.split("#");
// the 2nd item in the array will be the page
var page = urlSplit[1];
now you know the 'page', you can call whatever function that loads the page content
The #about is just pointing to a section within a page, not actually changing page. I'm guessing the onClick event refreshes the page with AJAX, and updates the URL shown to the user by changing document.location or similar.
Generally, I would say don't use AJAX for navigation. If you're changing to a different page, let the browser do a proper update, so the back button will work as the user expects it to. Use AJAX when you're dynamically altering portions of a page.
If you really want AJAX navigation, use window.location.hash, as suggested by strada.
But also be aware that IE can easily get into problems when using lots of Javascript language constructs. Circular references between javascript and DOM objects, and closures can quickly cause memory leaks. Other browsers also suffer but IE (including 9) seems to be worst affected. If you refresh the page, that makes it really easy for the browser to throw out all this stuff.
精彩评论