2017-04-25 24 views
0

給定一個網址www.site.com/test,我怎麼能路由到www.site.com/#testinner與JavaScript,沒有硬編碼基地網址?通過路由 - 我的意思是包括刷新/頁面加載。給定一個網址www.site.com/test,用javascript轉到www.site.com/#testinner,沒有硬編碼基址url

這給了我settings#lol

var desiredBase = window.location.protocol + "//" + window.location.host + "/"; 
var path = '#lol'; 
window.location.href = desiredBase + path; 
location.reload(); 
+0

你男人像'window.location.href = window.location.origin + '/' + path'? –

+0

@BenjiLees不重新加載。 – RobVious

+0

真的嗎?你在哪裏運行腳本?我只是把它放在我的瀏覽器控制檯中,它運行良好。您不必使用重新加載方法,該方法旨在重新加載當前頁面。 –

回答

1

您可以只搜索/test在的結尾,並與/#testinner更換。這裏是一個例子:

window.location.href = window.location.href.replace(/\/test$/, "/#testinner"); 

這是一個片段,顯示了基本的想法。您可以看到它自動導航到#testinner書籤,而無需刷新頁面。當然,代碼片段的網址並不是以/test結尾,所以我不得不修改它替換的內容,並且代碼段中不存在/#testinner,所以我必須稍微修改一下。但是這個概念是一樣的。我還在標記中包含了當前網址,因爲您無法在代碼段中輕鬆查看。

document.getElementById("currUrl").innerText = location.href; 
 

 
location.href = location.href.replace(/\/js$/, "/js#testinner"); 
 

 
document.getElementById("currUrl").innerText = location.href;
.vert-spacer { 
 
    height: 800px; 
 
}
<div class="vert-spacer"></div> 
 
<div id="testinner">Test Bookmark</div> 
 
Current URL: <span id="currUrl"></span>

+0

不起作用。需要刷新。 – RobVious

+0

它在Chrome 57中無需刷新就可以正常工作。真的,它在所有瀏覽器中都能正常工作,因爲它是HTML規範的一部分,更新位置應該觸發到指定URL的導航。 – Elezar

+0

我已經用一個代碼更新了答案,顯示它按預期工作 – Elezar

相關問題