本文详细解析 JavaScript 中 window.location 对象的各个属性,包括 pathname、href、port、protocol、hash、host 和 search,用于获取页面路径的不同部分。同时提供了多种通过 JS 实现网页刷新的代码示例,涵盖 history.go、location.reload 等方法,帮助开发者快速掌握前端路径处理与页面刷新技巧。
获取页面路径各属性详解
通过设置或获取对象指定的“文件名”或路径,可以使用以下代码: <script> alert(window.location.pathname) </script>
若要设置或获取整个 URL 为字符串,可执行: <script> alert(window.location.href); </script>
设置或获取与 URL 关联的端口号码,代码如下: <script> alert(window.location.port) </script>
设置或获取 URL 的协议部分,示例如下: <script> alert(window.location.protocol) </script>
设置或获取 href 属性中在井号“#”后面的分段,代码为: <script> alert(window.location.hash) </script>
设置或获取 location 或 URL 的 hostname 和 port 号码,可使用: <script> alert(window.location.host) </script>
设置或获取 href 属性中跟在问号后面的部分,参考以下代码: <script> alert(window.location.search) </script>
网页刷新方法示例
关于网页刷新的推荐 JS 实现方式,包括以下按钮点击事件: <input type=button value=刷新 onclick="history.go(0)"> <input type=button value=刷新 onclick="location.reload()"> <input type=button value=刷新 onclick="location=location"> <input type=button value=刷新 onclick="location.assign(location)"> <input type=button value=刷新 onclick="document.execCommand('Refresh')"> <input type=button value=刷新 onclick="window.navigate(location)"> <input type=button value=刷新 onclick="location.replace(location)"> <input type=button value=刷新 onclick="document.URL=location.href">