如何在Mozilla中更改浏览器URL而不进行页面引用

时间:2017-05-24 11:52:38

标签: javascript jquery

我使用下面的代码,但页面仍然刷新。 我正在尝试更改网址或网页而不刷新它。

//getting the url from browser
var uri = window.location.toString();
//checking whether the url has anything after '?'
if (uri.indexOf("?") > 0) 
//then take the url before '?'
var clean_uri = uri.substring(0, uri.indexOf("?"));

//And push this to browser
window.history.replaceState({}, document.title, clean_uri);

1 个答案:

答案 0 :(得分:0)

history.replaceState不应该刷新页面。如果页面正在重新加载,那么代码中还有其他内容,例如表单提交。 preventDefault()方法可以帮助您取消活动。

<form>
    <button id="bt" type="submit">Submit</button>
</form>


//getting the url from browser
var uri = window.location.toString();
var bt = document.getElementById("bt");

//checking whether the url has anything after "?"
if (uri.indexOf("?") > 0) {
    //then take the url before "?"
    var clean_uri = uri.substring(0, uri.indexOf("?"));
    bt.addEventListener("click", function (e) {
        e.preventDefault(); // If you remove this line, the page will refresh and the form will be submitted.
        history.replaceState({}, document.title, clean_uri); 
    });
}