点击按钮如何改变当前窗口的url

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
   <button id="openWindow">
       打开新窗口
   </button>
    <button id="hrefSwitchUrl">
        采用href 转换本页面的Url
    </button>
   <button id="replaceSwitchUrl">
       采用replace 转换本页面的Url
   </button>
   <button id="reload">
       采用reload 强迫浏览器刷新当前页面
   </button>
   <button id="back">
       通过浏览器返回之前的页面代码的实现
   </button>
   <p>
       location.href='http://www.xxx.com/';和location.replace('http://www.xxx.com/');
   </p>
   <p>两者的不同之处是前者会在浏览器的历史浏览记录(history对象中增加一条新的记录,而后者则是相当于用replace中的url代替了现有的页面url,并把history中的url也替换为重定向后的url。</p>
    <p>理解浏览器的历史记录:http://web.jobbole.com/88312/</p>
</body>
<script>
  document.getElementById("openWindow").addEventListener("click",function (ev) {
      window.open(window.location.href);
  })
  document.getElementById("hrefSwitchUrl").addEventListener("click",function (ev) {
      window.location.href="http://www.baidu.com";
  })
  document.getElementById("replaceSwitchUrl").addEventListener("click",function (ev) {
      window.location.replace("http://www.baidu.com");
  })
  document.getElementById("reload").addEventListener("click",function (ev) {
      window.location.reload("http://www.baidu.com");// 可选参数,默认为false
  })
  document.getElementById("back").addEventListener("click",function (ev) {
      window.history.back(-1);
  })
</script>
</html>

猜你喜欢

转载自www.cnblogs.com/ilimengyang/p/10371357.html