2013-08-27 138 views
0

我正在創建一個檢測並返回頁面名稱的腳本。 但是,當存在查詢字符串時,它不會返回「url_segment」所需的值。從URL段刪除查詢字符串

有人能告訴我怎樣才能去掉查詢字符串和變量「URL」和「url_segment」

// http://test.com/action 
// http://test.com/action/all 
// http://test.com/action/all?page=2 

function return_page_name() 
{ 
    var url = $(location).attr("href").split("/")[3]; // returns "action" 
    var url_segment = $(location).attr("href").split("/")[4]; // returns "all" (if selected) 

    if(url === "") 
    { 
     page = "homepage"; 
    } 
    else if(url === "signup") { 
     page = "sign-up"; 
    } 

    return page; 
} 
+0

避免的,這是沒有必要的。您可以使用'window.location.pathname'輕鬆獲取(並解析)路徑名。像現在這樣拆分它並獲取所需的元素。 –

+0

假設'location'實際上是['window.location'](https://developer.mozilla.org/en-US/docs/Web/API/window.location),那麼就不需要將它包裝在jQuery中。 –

+0

http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page –

回答

0

您可以使用此代碼返回值:

function Q() { 
    var q={}; 
    var a=window.location.search.substring(1); 
    var b=a.split("&"); 
    for (var i=0;i<b.length;i++) { 
     var c=b[i].split("="); 
     q[c[0]]=c[1]; 
    } 
    return q; 
} 

所以你可以執行它並獲得一個包含查詢字符串的對象,就像你使用PHP一樣。

0

見在這種情況下使用jQuery window.location.pathname

function getLastUrlSegment() { 
    return window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1); 
} 

// http://test.com/action 
window.location.pathname == '/action' 
getLastUrlSegment() == 'action' 

// http://test.com/action/all 
window.location.pathname == '/action/all' 
getLastUrlSegment() == 'all' 

// http://test.com/action/all?page=2 
window.location.pathname == '/action/all' 
getLastUrlSegment() == 'all' 
相關問題