我希望此链接仅在第一次点击时有用。从第二次点击它不会重定向到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>
答案 0 :(得分:1)
它不起作用的原因是因为您的浏览器会在您离开页面时删除所有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 "";
}
答案 1 :(得分:1)
@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!