如何在没有查询参数的情况下重新加载页面?

use*_*495 37 html javascript

假设我想重新加载 www.domain.com/abc?num=4

但我想重新加载www.domain.com/abc(没有问号后的所有内容)

Igo*_*mov 72

window.location = window.location.href.split("?")[0];
Run Code Online (Sandbox Code Playgroud)

  • 更好:`window.location = window.location.pathname` (47认同)
  • 值得注意的是,`window.location = window.location.pathname` 不是有效的 TypeScript 语法。您需要使用`window.location.href = window.location.pathname`。 (3认同)
  • @Noyo实际上这个答案适用于使用#来表示视图和路径(angular,GWT)的现代框架.pathname忽略了# (2认同)
  • 你提出了一个很好的观点,@ qbert65536,但这仍然更好(并避免函数调用):`window.location = window.location.pathname + window.location.hash;` (2认同)

小智 24

有几种方法可以解决它:

window.location = window.location.href.split("?")[0];
Run Code Online (Sandbox Code Playgroud)

或者,或者:

window.location = window.location.pathname;
Run Code Online (Sandbox Code Playgroud)

  • 我真的不明白这意味着什么,但在复制粘贴之前值得一读:https://developer.mozilla.org/en-US/docs/Web/API/URLUtils.pathname (3认同)

M_R*_*R_K 12

这是最好最简单的方法,

// similar to HTTP redirect
window.location.replace(location.pathname);
Run Code Online (Sandbox Code Playgroud)

  • 或者简称为“location.replace(location.pathname);”。 (2认同)

Noy*_*oyo 7

我通常会尽量避免进行不必要的函数调用,特别是当我需要的信息已经由DOM提供给我时.也就是说,这可能是客观上最好的解决方案:

window.location = window.location.pathname + window.location.hash;
Run Code Online (Sandbox Code Playgroud)

正如用户qbert65536 的评论中所指出的,有许多流行的现代框架使用哈希来表示视图和路径,这就是为什么单独使用是不够的.window.location.pathname


Zna*_*kus 5

试试这个 JavaScript:

location = location.pathname;
Run Code Online (Sandbox Code Playgroud)