2012-03-24 49 views
0

http://www.domainname.com/#changepasswordJQUERY HASH +如何傳遞額外變量

我需要傳遞一個帶有上面URL的額外變量。

我已經嘗試了一些方法,但我不確定要做到這一點如最好的辦法:

http://www.domainname.com/#changepassword?variable

我用下面的jQuery來捕捉HASH:

if (window.location.hash != '') { 
    var hash = window.location.hash.substring(1); 
    if(hash == 'changepassword') {  // Password Change 
     alert('changepassword'); 
    } 
} 

如何傳遞一個額外的變量與HASH?捕獲HASH和額外變量的最佳方法。

THX

+1

在你的代碼示例中有**沒有** jQuery ...這是計劃JavaScript – ManseUK 2012-03-24 07:41:30

+0

,但具有'jQuery'標記將使範圍在jQuery中回答。而那些避開'javascript'標籤的'jQuery'人將會看到它突出顯示! – tusar 2012-03-24 07:50:03

+0

@tusar我並沒有質疑標籤的需求(如果我認爲它不合適,我會編輯和刪除它) - 我只是陳述事實.... – ManseUK 2012-03-24 07:52:39

回答

0

你是混合location.hashlocation.search - see here for the explanation

你可以只使用location.hash並在你的「變量」之間加上一個分隔符:

例如..如果這是你的網址http://www.domainname.com/#changepassword-variable-another th恩,你可以做

var hash = window.location.hash.substring(1); 
var hasharray = hash.split['-'] 
if(hasharray[0] == 'changepassword') {  // Password Change 
    alert('changepassword'); 
} 

,或者您可以使用location.search和下面的例子:

網址:http://www.domainname.com/?command=changepassword&var=variable&var2=another

此使用key=value格式,然後用下面的方法來訪問values

function getQueryString() { 
    var result = {}, queryString = location.search.substring(1), 
     re = /([^&=]+)=([^&]*)/g, m; 

    while (m = re.exec(queryString)) { 
    result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]); 
    } 

    return result; 
} 

您可以通過傳遞函數key

var command = getQueryString()["command"]; 
if(command == 'changepassword') {  // Password Change 
    alert('changepassword'); 
} 
0
"#ffsf?sdff?sffsfd".match(/(?!\?)\w+/g) 

結果:

["ffsf", "sdff", "sffsfd"] // Array 

無論如何,你應該對你打算怎麼做更精確。