2016-06-10 79 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>