【问题标题】:jquery check if URL has a querystring alreadyjquery 检查 URL 是否已经有查询字符串
【发布时间】:2012-02-14 18:08:14
【问题描述】:
【问题讨论】:
标签:
javascript
jquery
string
url
【解决方案1】:
试试BBQ plugin for jQuery。如果您要像您的示例一样使用多个查询字符串值,那么它非常易于使用并且是最好的插件。
要获取变量,可以使用:
$.bbq.getState( "kwd" );
$.bbq.getState( "hos" );
并设置状态:
$.bbq.pushState({ hos: Carmel }); //pushState has an optional 2nd param
//for whether or not to delete all the params not in the push function or to keep them.
并在 URL 更改时执行函数:
$(window).bind( "hashchange", function(e) {
// In jQuery 1.4, use e.getState( "url" );
var url = $.bbq.getState( "url" );
});
【解决方案3】:
我讨厌只是链接到网站,但我找到了这个人的解决方案,它看起来非常适合通过 javascript 获取和设置 url 参数。
http://www.west-wind.com/weblog/posts/2009/Sep/07/Get-and-Set-Querystring-Values-in-JavaScript
//check if querystring contains hos
if (getUrlEncodedKey('hos', location.search) != '') {
//set new value
setUrlEncodedKey('hos', newval);
}
getUrlEncodedKey = function(key, query) {
if (!query)
query = window.location.search;
var re = new RegExp("[?|&]" + key + "=(.*?)&");
var matches = re.exec(query + "&");
if (!matches || matches.length < 2)
return "";
return decodeURIComponent(matches[1].replace("+", " "));
}
setUrlEncodedKey = function(key, value, query) {
query = query || window.location.search;
var q = query + "&";
var re = new RegExp("[?|&]" + key + "=.*?&");
if (!re.test(q))
q += key + "=" + encodeURI(value);
else
q = q.replace(re, "&" + key + "=" + encodeURIComponent(value) + "&");
q = q.trimStart("&").trimEnd("&");
return q[0]=="?" ? q : q = "?" + q;
}
//There are a couple of helpers in use here. For completeness here they are as well:
String.prototype.trimEnd = function(c) {
if (c)
return this.replace(new RegExp(c.escapeRegExp() + "*$"), '');
return this.replace(/\s+$/, '');
}
String.prototype.trimStart = function(c) {
if (c)
return this.replace(new RegExp("^" + c.escapeRegExp() + "*"), '');
return this.replace(/^\s+/, '');
}
String.prototype.escapeRegExp = function() {
return this.replace(/[.*+?^${}()|[\]\/\\]/g, "\\$0");
};
【解决方案4】:
只是一些代码提示,但未经测试。
$(".LocationDropDown").change(function(e){
var querystring=window.location.search;
var currentURL=$(location).attr('href');
if(querystring=='') {
window.location.href= ( $(this).val() == "All Hospitals" ) ? 'http://mysitee/events/Pages/default.aspx':'http://mysite/events/Pages/default.aspx?hos='+$(this).val();
}
else if(str.indexOf("hos=")==-1)
{
window.location.href = ( $(this).val() == "All Hospitals" ) ? 'http://mysitee/events/Pages/default.aspx':currentURL+'&hos='+$(this).val();
}
else{
window.location.href= ( $(this).val() == "All Hospitals" ) ? 'http://mysitee/events/Pages/default.aspx': getReplacedValForHospital(currentURL, $(this).val());
}
});
function getReplacedValForHospital(currentURL, hospitalVal) {
var tempString = currentURL.substring(currentURL.indexOf("hos="));
currentURL = currentURL.replace(tempString,"hos="+hospitalVal);
return currentURL;
}