2016-06-28 56 views
1

我試圖更新我當前的URL在身旁我點擊()函數更新URL的onclick

var str = window.location; // http://localhost:8888/000D6766F2F6/10001/edit/private/basic 
var new_str = str.replace("basic", "a"); 
alert(new_str); 
location.href = new_str; 

我一直得到

enter image description here


難道我做我不想在這裏做的任何事情?

回答

3

你就近了。您的替換語句會提前更改URL。

var new_str = window.location.href.replace("basic", "a"); 
alert(new_str); 
window.location.href = new_str; 
1

您需要從window.location的獲得屬性 'href' 屬性:

var str = window.location.href; // << Get href 
var new_str = str.replace("basic", "a"); 
alert(new_str); 
location.href = new_str; 
2

window.location不是字符串,它只是一個字符串表示。因此,您所調用的.replace方法不是String.replace方法。它實際上是the location replacement method,它導航到新頁面而不添加新的歷史記錄並且不會返回任何內容/ undefined

如果你將其轉換爲String(或訪問相當於.href屬性)您的代碼將工作:

var str = String(window.location); // http://localhost:8888/000D6766F2F6/10001/edit/private/basic 
var new_str = str.replace("basic", "a"); 
alert(new_str); 
location.href = new_str;