最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - javascript equivalent of anchor href - Stack Overflow

programmeradmin1浏览0评论

Let's say my webpage is http://localhost/myApp/route/index.html

if I click on:

  <li><a href="#secondpage">go to second page</a></li>

It will change the route to http://localhost/myApp/route/index.html#/secondpage without reloading.

Now I'm trying to do the same thing but with just onclick and javascript instead of anchor tag. Because I need to do something first before I let angular router change to another template.

  <li><a onClick="myFunction()">Payroll Run History</a></li>

  myFunction(){
      [... do stuff ...]
      //change to http://localhost/myApp/route/index.html#/secondpage   without reloading page
  }

Let's say my webpage is http://localhost/myApp/route/index.html

if I click on:

  <li><a href="#secondpage">go to second page</a></li>

It will change the route to http://localhost/myApp/route/index.html#/secondpage without reloading.

Now I'm trying to do the same thing but with just onclick and javascript instead of anchor tag. Because I need to do something first before I let angular router change to another template.

  <li><a onClick="myFunction()">Payroll Run History</a></li>

  myFunction(){
      [... do stuff ...]
      //change to http://localhost/myApp/route/index.html#/secondpage   without reloading page
  }
Share Improve this question edited Jun 10, 2016 at 22:27 Robert Moskal 22.6k8 gold badges68 silver badges90 bronze badges asked Jun 10, 2016 at 22:17 user308553user308553 1,2504 gold badges18 silver badges33 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

To set the anchor property:

location.hash = "#/secondpage";

First of all, don't use onclick attribute, browsers and pop-up blockers don't like it. Give an ID to your element and create an event listener in JavaScript.

document.getElementById('my_link').addEventListener("click", function(event) {
  // Prevent defualt action of event:
  event.preventDefault();

  // Do your extra stuff here...
 
  location.hash = event.target.getAttribute('href').substr(1);
});
<a href="#/secondpage" id="my_link">Click here</a>

If you are looking to navigate to a second page instead of a section of a page..you can use window.location

here is an example

document.getElementById('click').onclick=function(){
var div=document.createElement('div');
div.innerHTML='I just append this div before changing my location';
document.body.appendChild(div);
window.location='http://www.google.';
}
#click:hover{
  cursor:pointer;
}
<li id='click'>Click here</li>

You will notice I added a div to the body tag and then change my location....

window.location.hash = "secondpage";

It will set the #secondpage in the URL and will scroll to that ID.

发布评论

评论列表(0)

  1. 暂无评论