location对象

<p>语法:location.href</p>
<p>功能:返回当前加载页面的完整URL</p>
<p>location.href与window.location.href</p>
<p>说明:location.href与window.location.href等价</p>
<p>语法:location.hash</p>
<p>功能:返回URL中的hash(#号后跟零或多个字符),如果不包含则返回空字符串</p>
<p>语法:location.host</p>
<p>功能:返回服务器名称和端口号(如果有)</p>
<p>语法:location.hostname</p>
<p>功能:返回不带端口号的服务器名称</p>
<p>语法:location.pathname</p>
<p>功能:返回URL中的目录和(或)文件名</p>
<p>语法:location.port</p>
<p>功能:返回URL中指定的端口号,如果没有,返回空字符串</p>
<p>语法:location.protocol</p>
<p>功能:返回页面使用的协议</p>
<p>语法:location.search<strong style="color: red">(比较常用)</strong></p>
<p>功能:返回URL的查询字符串。这个字符串以问号开头</p>

location.hash例子:

<div class="box1" id="top"></div>
    <div class="box2"></div>
    <input type="button" id="btn" value="返回顶部">
    <script type="text/javascript">
    console.log(location.href)
    var btn = document.getElementById("btn");
    btn.onclick = function() {
        location.hash = "#top"; //设置锚点,锚链接
    }
    </script>

<h3>1.掌握位置操作</h3>
<h3>2.掌握location.reaplace()</h3>
<h3>3.掌握location.reload()</h3>

location.href与location.replace()例子:

<script type="text/javascript">
           setTimeout(function(){
               // location.href="http://www.baidu.com" //浏览器上面回退按钮显示
               // window.location.href="http://www.baidu.com" 
               location.replace("http://www.baidu.com")//浏览器上面回退按钮不显示不可点击
           },1000)
       </script>

<h2>location.replace()</h2>
<p>语法:location.replace(url)</p>
<p>功能:重新定向URL</p>
<p>说明:使用location.replace不会在历史记录中生成新记录</p>
<h2>location.reload()</h2>
<p>语法:location.reload()</p>
<p>功能:重新加载当前显示的页面</p>
<p>说明:</p>
<p>location.reload()有可能从缓存中加载</p>
<p>location.reload(true)从服务器重新加载</p>

location.reload()例子:

<script type="text/javascript">
           var btn = document.getElementById("btn");
        btn.onclick = function() {
            // location.reload(); //从新加载页面
            location.reload(true); //强制从服务器上刷新
        }
       </script>
原文地址:https://www.cnblogs.com/huanghuali/p/9791549.html