Javascript 将参数附加到当前 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8737615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:16:37  来源:igfitidea点击:

Append a param onto the current URL

javascriptjqueryappend

提问by Fuego DeBassi

I'd like to have a little easter egg button in the corner of a project site. When clicked, it just drops a string onto the current url and reloads the page.

我想在项目站点的角落里放一个小复活节彩蛋按钮。单击时,它只是将一个字符串放到当前 url 上并重新加载页面。

So if I'm on: http://test.com/projects/view/134

所以如果我在:http: //test.com/projects/view/134

The button is clicked

按钮被点击

Page reload on: http://test.com/projects/view/134?ts=true

页面重新加载:http: //test.com/projects/view/134?ts=true

Not really sure how I might go about doing so though.

不太确定我会如何去做。

回答by Chamika Sandamal

try this code,

试试这个代码,

var separator = (window.location.href.indexOf("?")===-1)?"?":"&";
window.location.href = window.location.href + separator + "ts=true";

EDITS: to avoid duplicated parameter or very large string in your url, you need to replace the old param it already exists.

编辑:为避免 url 中的重复参数或非常大的字符串,您需要替换它已经存在的旧参数。

var url=window.location.href,
    separator = (url.indexOf("?")===-1)?"?":"&",
    newParam=separator + "ts=true";
    newUrl=url.replace(newParam,"");
    newUrl+=newParam;
    window.location.href =newUrl;

回答by Adam Rackis

You can assign location.hrefto the value it currently has, plus your new querystring:

您可以将location.href分配给它当前拥有的值,以及您的新查询字符串:

(edited to be friendly to existing querystrings)

(编辑为对现有查询字符串友好)

$("#yourButtonId").click({
    var loc = location.href;
    if (loc.indexOf("?") === -1)
       loc += "?";
    else
       loc += "&";
    location.href = loc + "ts=true";
});

Or to be more succinct:

或者更简洁:

$("#yourButtonId").click({
    var loc = location.href;        
    loc += loc.indexOf("?") === -1 ? "?" : "&";

    location.href = loc + "ts=true";
});

回答by Vianney Bajart

Using:

使用:

Example:

例子:

var url = new URL("http://foo.bar/?x=1&y=2");

// If your expected result is "http://foo.bar/?x=1&y=2&x=42"
url.searchParams.append('x', 42);

// If your expected result is "http://foo.bar/?x=42&y=2"
url.searchParams.set('x', 42);

// Build result
url.toString();

回答by harttle

Make full use of the locationDOM API, and count in hash:

充分利用locationDOM API,进行hash计数:

location.protocol + '//' + location.hostname + location.pathname + 
    (location.search ? location.search + '&a=b' : '?a=b') +
    location.hash;

回答by Bobbzorzen

I found the previous answers lacking and as such here is a method that better handles other parameters in current querystring

我发现缺少以前的答案,因此这里有一种方法可以更好地处理当前查询字符串中的其他参数

appendToQueryString = function (param, val) {
    var queryString = window.location.search.replace("?", "");
    var parameterListRaw = queryString == "" ? [] : queryString.split("&");
    var parameterList = {};
    for (var i = 0; i < parameterListRaw.length; i++) {
        var parameter = parameterListRaw[i].split("=");
        parameterList[parameter[0]] = parameter[1];
    }
    parameterList[param] = val;

    var newQueryString = "?";
    for (var item in parameterList) {
        if (parameterList.hasOwnProperty(item)) {
            newQueryString += item + "=" + parameterList[item] + "&";
        }
    }
    newQueryString = newQueryString.replace(/&$/, "");
    return location.origin + location.pathname + newQueryString;
}

You have to use location.href = appendToQueryString(ts, true)to actually reload the page.

您必须使用location.href = appendToQueryString(ts, true)来实际重新加载页面。

回答by Sudhir Bastakoti

Do you mean:

你的意思是:


$(document).ready(function() {
    $("#yourButtonId").click(function() {
       var currentUrl = window.location.pathname + "?ts=true";
    });
});


回答by fabiangebert

If you want to account for the potential existence of a hash "#" in the URL, proceed as follows:

如果要考虑 URL 中可能存在的哈希“#”,请执行以下操作:

var href = location.href;
var hasQuery = href.indexOf("?") + 1;
var hasHash = href.indexOf("#") + 1;
var appendix = (hasQuery ? "&" : "?") + "ts=true";
location.href = hasHash ? href.replace("#", appendix + "#") : href + appendix;

回答by Ohas

location.href += '?ts=true';  

Just like that.

就这样。

回答by Babacar Diop

See the documentation of the history API :

请参阅历史 API 的文档:

https://developer.mozilla.org/en-US/docs/Web/API/History_API

https://developer.mozilla.org/en-US/docs/Web/API/History_API

Example of usage:

用法示例:

var obj = { Title: title, Url: url }; history.pushState(obj, obj.Title, obj.Url);

var obj = { Title: title, Url: url }; history.pushState(obj, obj.Title, obj.Url);

回答by Envil

An improvement from @Bobbzorzen answer, with ability to delete param by passing its name only:

@Bobbzorzen 答案的改进,能够通过仅传递其名称来删除参数:

function AlterQueryString(param, val) {
    var queryString = window.location.search.replace("?", "");
    var parameterListRaw = queryString == "" ? [] : queryString.split("&");
    var parameterList = {};
    for (var i = 0; i < parameterListRaw.length; i++) {
        var parameter = parameterListRaw[i].split("=");
        if (typeof val != 'undefined') {
            parameterList[parameter[0]] = parameter[1];
        } else if (param != parameter[0]) {
            parameterList[parameter[0]] = parameter[1];
        }
    }
    if (typeof val != 'undefined') {
        parameterList[param] = val;
    }

    var newQueryString = Object.keys(parameterList).length > 0 ? "?" : "";
    for (var item in parameterList) {
        if (parameterList.hasOwnProperty(item)) {
            newQueryString += item + "=" + parameterList[item] + "&";
        }
    }
    newQueryString = newQueryString.replace(/&$/, "");
    return location.origin + location.pathname + newQueryString;
}

gist: https://gist.github.com/envil/bc1832503bef55ffdabb0cde32bb06f1

要点:https://gist.github.com/envil/bc1832503bef55ffdabb0cde32bb06f1