简体   繁体   中英

How to go to a link using the href value in JavaScript?

Due to design considerations I cannot put an Anchor tag around elements but I can add a click event to those elements.

How can I follow the link correctly?

Previous code:

<a href="Page1.html">
   <button>Page 1</button>
</a>

New code:

<button onclick="document.location.href= 'Page1.html'">Page 1</button>

With the code above testing locally I go from:

file://directory/to/home.html

to

file://Page1.html

But the page is in the same directory at:

file://directory/to/Page1.html

In other words I have to proceed without being able to use an anchor tag but do my best to represent it.

Should I add a title with the page location to show the target location? Is there a way to simulate the location that shows in the footer when hovering over a link?

Use a relative path instead:

<button onclick="document.location.href='./Page1.html'">Page 1</button>

Even better, attach the listener properly using Javascript, since inline handlers are generally considered to be pretty poor practice, and have scoping and escaping issues:

document.querySelector('button').addEventListener('click', () => {
  window.location.href = './Page1.html';
});

You can use similar syntax to navigate up a level, without going all the way back to the root directory. Eg

window.location.href = '../Page1.html';

when running on

file://directory/to/home.html

will take you to

file://directory/home.html
  • ./ Denotes your current directory's path
  • ../ Denotes your previous directory's path
  • / Denotes your root path

In above case you should add current Directory's path:

<button onclick="window.location.href='./Page1.html'">Page 1</button>

./Page%201 => will take you to file://directory/to/home.html

../Page%201 => file://directory/home.html

/Page%201 => file://Page%201

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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