我使用下面的代码,但页面仍然刷新。 我正在尝试更改网址或网页而不刷新它。
//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);
答案 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);
});
}