2016-06-10 80 views
-1

的等效比方说,我的网页是http://localhost/myApp/route/index.htmlJavaScript的锚HREF

如果我点击:

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

将路线更改为http://localhost/myApp/route/index.html#/secondpage无需重新加载。

现在我试图做同样的事情,但只是onclick和JavaScript而不是锚标记。因为我需要先让角色路由器更改为另一个模板之前先做些事情。

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

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

回答

3

要设置锚属性:

location.hash = "#/secondpage"; 
1

如果您正在寻找导航到第二页,而不是page..you的部分可以在这里使用了window.location

是一个例子

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>

你会发现我添加一个div body标签,然后更改我的位置....

1
window.location.hash = "secondpage"; 

它将为在URL中#secondpage,将滚动到该ID。

2

首先,不要使用onclick属性,浏览器和弹出窗口阻止程序不喜欢它。给你的元素添加一个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>