繁体   English   中英

链接仅在第一次点击时有效,而从第二次点击开始将不会重定向到href中指定的页面

[英]link will work only on 1st click and from 2nd click will not redirect to the page which is specified in href

我希望此链接仅在第一次点击时有效。 从第二次单击,它将不会重定向到a.php,并且在单击超链接后将保留在同一页面上。

<script>
  var j=0;
  function a()
  {
      if(j==0)
      {
          window.location.href="a.php";
          j=1;
      }
      else
      {
           window.location.href="t.html";
      }

  }
 </script>
<a href="a.php" onclick="a()">hi</a>

它不起作用的原因是,当您离开页面时,浏览器会删除所有JavaScript变量。

我建议使用JavaScript cookie 然后,您可以保留这些变量,直到浏览器删除所有cookie为止。
要设置cookie ,请调用以下方法:

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

...并获得Cookie:

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return "";
}

@Okx说的很正确,但是使用localStorage在从IE8开始的所有浏览器上都可以正常工作。

function a() {
  var count = parseInt(localStorage.count_of_a, 10); 
  if (isNaN(count)) count = 0; 
  if (count == 0) {
    count += 1; 
    localStorage.count_of_a = count;
    window.location = 'a.php';
  } else {
    window.location = 't.html'; 
  }
}
// Note 1: this won't work if Javascript is disabled!
// Note 2: people can reset their local storage and rewrite the variables
//         themselves!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM