Activar evento onClick () con enlaces directos

I have a website with a navigation bar. When a link is clicked, it uses the onClick() handler 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 However, when linked directly to it opens the default index.php .

How do I directly link to the pages, as if it was onClick()?

preguntado el 27 de agosto de 11 a las 22:08

4 Respuestas

You can call the function used in onclick on page load.


will give you #about in your example, so you can load(or show) the relevant content.

Respondido 28 ago 11, 02:08

You need get the #something on page load, and then if it is found, call your onclick funcionar con él.

tag = /#[^\s]+/.exec(document.location.href);
tag = tag.substring(1);
// you have what you want

Respondido 28 ago 11, 02:08

Beautiful, but how come in order to have to have the proper content loaded, I have to send the link with the #whatever ¿dos veces? - Jason

so you're loading in content with Ajax?

A quick and dirty way to do this would be to look at the url


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

Respondido 28 ago 11, 02:08

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.

Respondido 28 ago 11, 02:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.