2012-03-24 51 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 

无论如何,你应该对你打算怎么做更精确。