使用jquery从URL中删除查询字符串(使用问题)

Bha*_*jan 5 javascript jquery

在我的网站博客页面中,在该页面URL中添加了查询字符串.我想从URL中删除查询字符串.所以我曾经使用jquery,我写了并添加到我的脚本中.它会删除查询字符串,但会在第n次刷新页面.我习惯了"一个"jquery方法.这也行不通.

你能帮助我吗

我的剧本是

jQuery(document).one('ready',function(){
    window.location.href = window.location.href.split('?')[0];
});
Run Code Online (Sandbox Code Playgroud)

小智 7

var uri = window.location.href.toString();
if (uri.indexOf("?") > 0) {
    var clean_uri = uri.substring(0, uri.indexOf("?"));
    window.history.replaceState({}, document.title, clean_uri);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您可以在代码中添加解释性文本以改进您的答案,使其对所有用户更有帮助,那就太好了 (3认同)
  • 这应该被标记为正确答案! (2认同)

小智 6

将值设置为 window.location.href 将重新加载页面。尝试这个:

    var url = window.location.href;
    var a = url.indexOf("?");
    var b =  url.substring(a);
    var c = url.replace(b,"");
    url = c;
Run Code Online (Sandbox Code Playgroud)


Beg*_*ner 5

继续刷新页面直到第 n 次。

这是因为您没有检查 URL 是否具有查询字符串。所以是无限刷新。

你可以试试这个:

$(document).ready(function(){
    if (window.location.href.indexOf('?') > -1) {
        window.location.href = window.location.pathname;
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑 1:是否可以在不刷新页面的情况下删除查询字符串?

你可以试试这个:

$(document).ready(function(){
    if (window.location.href.indexOf('?') > -1) {
        history.pushState('', document.title, window.location.pathname);
    }
});
Run Code Online (Sandbox Code Playgroud)