Javascript提示验证?

时间:2014-04-16 02:19:42

标签: javascript validation switch-statement conditional-statements prompt

我想提示用户输入一项运动(棒球,足球,足球或赛道)。假设我输入“高尔夫”。在进入其中一项有效的运动之前,如何让它继续让我参加运动?这项运动决定了他们在哪个领域上演。以下是我的代码。

var sport = prompt("What sport do you play? (Baseball, Football, Soccer, or Track)").toLowerCase (); 

switch (sport) {
    case "baseball": 
        field = "Field 1";
        break;
    case "football": 
        field = "Field 2";
        break;
    case "soccer":
        field = "Field 3";
        break;
    case "track":
        field = "Field 4";
        break;
    default: alert("Please enter a valid sport");
}

1 个答案:

答案 0 :(得分:2)

loop:
while(true){
    var sport = prompt("What sport do you play? (Baseball, Football, Soccer, or Track)").toLowerCase(); 
    switch (sport) {
        case "baseball": 
            field = "Field 1";
            break loop;
        case "football": 
            field = "Field 2";
            break loop;
        case "soccer":
            field = "Field 3";
            break loop;
        case "track":
            field = "Field 4";
            break loop;
        default: alert("Please enter a valid sport");
    }
}

var field;
while(true){
    var sport = prompt("What sport do you play? (Baseball, Football, Soccer, or Track)").toLowerCase();
    if(!sport || /^(baseball|football|soccer|track)$/.test(sport)){
        field = "Field " + ("baseball|football|soccer|track".split("|").indexOf(sport)+1);
        break;
    }else{
        alert("Please enter a valid sport");
    }
}