简体   繁体   English

相当于锚href的javascript

[英]javascript equivalent of anchor href

Let's say my webpage is http://localhost/myApp/route/index.html 假设我的网页是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. 它将路由更改为http://localhost/myApp/route/index.html#/secondpage而无需重新加载。

Now I'm trying to do the same thing but with just onclick and javascript instead of anchor tag. 现在,我尝试执行相同的操作,但仅使用onclick和javascript而不是锚标记。 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
  }

设置锚属性:

location.hash = "#/secondpage";

First of all, don't use onclick attribute, browsers and pop-up blockers don't like it. 首先,不要使用onclick属性,浏览器和弹出窗口阻止程序都不喜欢它。 Give an ID to your element and create an event listener in JavaScript. 为您的元素提供一个ID,并使用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 如果要导航到第二页而不是页面的一部分,则可以使用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.com'; } 
 #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.... 您会注意到我在body标签上添加了div,然后更改了我的位置。...

window.location.hash = "secondpage";

它将在URL中设置#secondpage ,并将滚动到该ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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