1

我有这个网址

http://9001/transactions

我有需要更改网址的按钮,例如

http://9001/transactions?type=all
http://9001/transactions?type=confirmed
http://9001/transactions?type=unconfirmed

交易后我将如何替换字符串。我有点击功能,只需要知道在里面放什么。

url 会改变,所以这不能依赖于交易之前的任何东西(如果有意义的话)。抱歉,如果问题含糊不清,但急于完成这项工作。

4

4 回答 4

1

您可以构建一个函数来更改 GET 参数...

var updateGetParam = function(key, value) {

    window.location.search = window.location.search.replace(new RegExp("([?&;])" + key + "=.*?(&|;|$)"), "$1" + key + "=" + encodeURIComponent(value) + "$2");

}

js小提琴

您应该首先通过正则表达式转义函数运行用户输入。

于 2012-09-26T13:09:07.253 回答
1

我写了一个函数来完成这个,它重新加载当前页面,并且完全支持更改现有的 url 变量(以及添加新变量)。您所要做的就是将对象文字传递给函数。见这里:https ://stackoverflow.com/a/10235376/733347

在你的情况下,你需要做的就是调用函数

reloadWithQueryStringVars({"type": "all"});

或者

reloadWithQueryStringVars({"type": "confirmed"});

或者

reloadWithQueryStringVars({"type": "unconfirmed"});

关于按钮的点击事件

这是整个函数供参考:

function reloadWithQueryStringVars (queryStringVars) {
    var existingQueryVars = location.search ? location.search.substring(1).split("&") : [],
        currentUrl = location.search ? location.href.replace(location.search,"") : location.href,
        newQueryVars = {},
        newUrl = currentUrl + "?";
    if(existingQueryVars.length > 0) {
        for (var i = 0; i < existingQueryVars.length; i++) {
            var pair = existingQueryVars[i].split("=");
            newQueryVars[pair[0]] = pair[1];
        }
    }
    if(queryStringVars) {
        for (var queryStringVar in queryStringVars) {
            newQueryVars[queryStringVar] = queryStringVars[queryStringVar];
        }
    }
    if(newQueryVars) { 
        for (var newQueryVar in newQueryVars) {
            newUrl += newQueryVar + "=" + newQueryVars[newQueryVar] + "&";
        }
        newUrl = newUrl.substring(0, newUrl.length-1);
        window.location.href = newUrl;
    } else {
        window.location.href = location.href;
    }
}
于 2012-09-26T13:18:40.403 回答
0

看看这段代码是否适合你:

var href = window.location.href;

// This assumes the value of your button is the action and each
// button has the class button applied. Modify as necessary
$('.button').click(function (event) {
    if (href.lastIndexOf('?') !== -1) {
        href.replace(/\?(.*)/, '?type=' + $(this).val());
    } else {
        href += '?type=' + $(this).val();
    }
    window.location.href = href;
});
于 2012-09-26T13:10:58.517 回答
0

一个非常粗略的解决方案,但更容易理解和实施,看看它是否有帮助

var url = "http://9001/transactions?type=unconfirmed"; //in live environment, replace with var url = window.location.href;
var urlArray = url.split('?');
var urlArrayLength = url.split('?').length;


urlArray[urlArrayLength - 1] = "type=newValue";


url  = urlArray.join('?');

alert(url)
于 2012-09-26T13:20:10.950 回答