2011-09-06 29 views
3

點擊一個按鈕時,我該如何刪除網址的查詢字符串?我的網址是這樣的:如何刪除buttonclick上的查詢字符串?

www.mysite.com/?tx_felogin_pi1[forgot]=1

此頁面顯示爲獲得新密碼的形式,一切都是overlaybox內。當用戶突然再次記住他的用戶數據時,我需要在框中提供一個鏈接返回到登錄表單(也在overlaybox內),但我無法使用修復網址,因爲鏈接(和overlaybox)應該每個頁面都可以訪問。所以我需要一個鏈接去除查詢字符串,之前的url獨立。

我想這一點,但它不會工作:

function getPathFromUrl(url) { 
     return url.split("?")[0]; 
    } 
    // from http://stackoverflow.com/questions/2540969/remove-querystring-from-url 

    $("#querystring").click(getPathFromUrl); 

在我的控制檯中的錯誤是:url.split不是一個函數...

回答

17

什麼是url?你必須從window.location對象獲取的網址:

$("#querystring").click(function(){ 
    window.location.href = window.location.href.split('?')[0]; 
}); 
+0

的感謝!它工作正常 – sinini

+0

高超的+1爲您的答案 –

+1

它重新加載頁面。 –

0
$("#querystring").click(function(){ 
    // you can use url.split("?")[0]; here, however be sure it's in global scope 

}); 
1

,以便獲得url查詢字符串不使用這種

function getPathFromUrl() { 
    var url = window.location.href; 

    if(url.indexOf("?") != -1) 
    url = url.split("?")[0]; 

    return url; 
} 

使用

$("#querystring").click(function(){ 
    alert(getPathFromUrl());//this will alert the url without querystring 
}); 
+1

不需要確定該字符串是否包含「?」。 ''test'.split('?')[0]'將返回'test'。 –

+0

那是正確的,但爲什麼「拆分」它不包含'?'? – ShankarSangoli

+1

因爲,雖然我沒有測試它,但我懷疑'split'比'indexOf'更昂貴(除了最有可能運行它們的事實)。爲什麼要像這樣纏繞你的代碼? –