Append a param onto the current URL

2019-01-22 19:40发布

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.

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

The button is clicked

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

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

10条回答
闹够了就滚
2楼-- · 2019-01-22 20:25
location.href += '?ts=true';  

Just like that.

查看更多
Lonely孤独者°
3楼-- · 2019-01-22 20:29

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

(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";
});
查看更多
爷的心禁止访问
4楼-- · 2019-01-22 20:29

Do you mean:


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


查看更多
Bombasti
5楼-- · 2019-01-22 20:29

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

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;
查看更多
登录 后发表回答