Javascript开关无法正常工作

时间:2012-09-12 15:08:43

标签: javascript switch-statement

我有以下代码:

var windowNow = window.localStorage.getItem("windowNow");
switch(windowNow)
{
case 1:
    var link = "http://www.zive.sk/rss/sc-47/default.aspx";
    var listviewID = "feedZive";
    break;
case 2:
    var link = "http://mobilmania.azet.sk/rss/sc-47/default.aspx";
    var listviewID = "feedMobil";
    break;
case 3: 
    var link = "http://www.automoto.sk/rss";
    var listviewID = "feedAuto";
    break;
}

我知道windowNow === 1,因为我已经通过警告检查了它,并确保它真的是1我用if(windowNow == 1) { alert ("Window now is 1");}检查了它并且它有效。但它在我的交换机内部无效(通过警报检查)。

2 个答案:

答案 0 :(得分:7)

localStorage中的项目始终是字符串。使用case "1"等等。

检查的问题是检查是否松散,不检查数据类型。你应该试过

if(windowNow === 1) { alert ("Window now is 1");}

注意三联=

答案 1 :(得分:1)

不要在交换机内声明变量。在开关外面声明它们并在内部分配。也先转换为整数。

var windowNow = parseInt(window.localStorage.getItem("windowNow"), 10), link, listviewID;
switch(windowNow)
{
case 1:
    link = "http://www.zive.sk/rss/sc-47/default.aspx";
    listviewID = "feedZive";
    break;
case 2:
    link = "http://mobilmania.azet.sk/rss/sc-47/default.aspx";
    listviewID = "feedMobil";
    break;
case 3: 
    link = "http://www.automoto.sk/rss";
    listviewID = "feedAuto";
    break;
default:
    // default assignment.
}