我有一个事件列表页面,可以使用查询字符串变量按类型和日期进行过滤。
我正在尝试使用 javascript/jQuery 实现以下逻辑。
我有一个日历,更新时会触发一个函数。当被解雇时,我需要实现以下逻辑:
- 如果当前网址包含
?filter=
,则将&dateStart=
添加到网址末尾。 - 如果当前网址包含
?filter=
AND&dateStart=
,则保留当前过滤器值,但将日期查询字符串替换为新的值。 - 如果当前网址仅包含
?dateStart=
,则将其替换为新网址。
我尝试了各种方法来实现此目的,但我一直遇到将信息附加到 URL 末尾而不是替换部分内容的问题。
如有任何帮助,我们将不胜感激。
谢谢。
最佳答案
你可以尝试这样的事情:
注意:未经测试。
var newDateValue;
var myPath = window.location.pathname
//check if path contains the different variables
var containsFilter = myPath.indexOf("?filter=") != -1 ? true : false;
var containsAppendedDateStart = myPath.indexOf("&dateStart=" != -1 ? true : false;
var containsDateStart = myPath.indexOf("?dateStart=" != -1 ? true : false;
if(containsFilter && !containsAppendedDateStart){
// If the current URL contains ?filter= then add &dateStart= to the end of the URL.
window.location.replace(window.location.href + "&dateStart=");
}else if(containsFilter && containsAppendedDateStart){
//If the current URL contains ?filter= AND &dateStart= then keep the current filter value but replace the date query string with a new one.
newDateValue = 10; // add your new value here
var splittedPathArray = myPath.split("&dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "&dateStart=" + addNewValue;
window.location.replace(newUrl);
}else if(containsDateStart){
// If the current URL contains ONLY ?dateStart= then replace it with the new one.
newDateValue = 15;// add your new value here
var splittedPathArray = myPath.split("?dateStart=");
var newUrl = window.location.protocol + "//" + window.location.host + "/" + splittedPathArray[0] + "?dateStart=" + addNewValue;
}
关于Javascript URL 查询字符串逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35574064/