为什么重定向页面在同一设备的3个视图后无效?

时间:2014-04-24 23:28:25

标签: javascript html local-storage server-side

如果用户在同一网页上出现3次,我会使用下面的javascript将用户重定向到其他网页,但不幸的是,它无法正常工作。

var count = Number( localStorage.visitCount );

if(!isNaN(count) {
   localStorage.visitCount = 1
} else {
   localStorage.visitCount++
}

if( localStorage.visitCount === 3 ) {
   window.location.replace('http://stackoverflow.com')
}

重定向不起作用。有人能告诉我我做错了什么吗?谢谢。

5 个答案:

答案 0 :(得分:2)

试试这个:

var count = Number( localStorage.visitCount );

if(isNaN(count)) { // <-- you forget bracker here
   localStorage.visitCount = 1
} else {
   localStorage.visitCount++
}

if( localStorage.visitCount >= 3 ) {
   window.location.replace('http://stackoverflow.com')
}

另外,正如Eric J.在this answer中所说的那样,它在第一个if中看起来是个逻辑错误。它应该是isNaN(count),而不是!isNaN(count)。他的回答是解释。

另外,正如gilly3在帖子中提到的那样,当localStorage.visitCount大于3时,你必须处理情况。

if( localStorage.visitCount > 3 ) {
   // handler for this situation
}

答案 1 :(得分:2)

该行

if(!isNaN(count) {

应该是

if(isNaN(count)) {

当它不是一个数字时,你没有将count初始化为1。相反,当它是非数字时,你试图增加它。

此外,您缺少一个右括号(我的更正行记录了这一点)。

答案 2 :(得分:0)

所以,这里有几件小事。

首先,您的语法已关闭。看起来你错过了一个&#34;)&#34;在你的if语句中,以及一些缺少的冒号。

其次,我也看到了一些逻辑错误。

在if语句中,如果它不是数字,您希望将计数设置为1,因此请删除&#34;!&#34;。否则它将与你想要的相反。

同样在你的第二个if语句中,你想要检查数字是否大于或等于三,否则它只会在第三次重定向而不是之后。

var count = Number(localStorage.visitCount);

if(isNaN(count)) {
   localStorage.visitCount = 1;
} else {
   localStorage.visitCount++;
}

if(localStorage.visitCount >= 3) {
   window.location.replace('http://stackoverflow.com');
}

答案 3 :(得分:0)

我算上3或4个问题:

  1. 语法错误 - 您缺少)
  2. 逻辑错误 - 在!之前丢失isNaN()(或保留它并使用!isFinite()
  3. 类型比较 - ===狂热者已经说服你永远不要使用==。在这种情况下,您需要==,因为localStorage变量始终是字符串,"3" === 3返回false
  4. 第4次访问会发生什么?如果您想重定向第3次和后续访问,则应使用>=

答案 4 :(得分:0)

使用以下代码:

<script>
var count = Number( localStorage.visitCount );

if(isNaN(count)) { // <-- you forget bracker here
   localStorage.visitCount = 1
} else {
   localStorage.visitCount++
}

if( localStorage.visitCount == 3 ) {
   window.location.replace('http://www.website.com')
}

if( localStorage.visitCount >= 3 ) {
   window.location.replace('http://www.website.com')
}
</script>

谢谢你们!