且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有输入文本的 Javascript switch 语句

更新时间:2023-11-14 14:48:52

我建议:

<script>

document.getElementById("clicker").onclick = function() {
    var scenario = document.getElementById('scenario').value; 
    var answers = {
        "1": "How are you?",
        "2": "whatevers",
        "3": "i don't know",
        "4": "today is your lucky day",
        "5": "This is the worse case scenario"
    };
    var str = answers[scenario];
    if (str) {
        document.getElementById("answer").innerHTML = str;
    }
}

</script>

主要的修复是您从带有 .value 属性的 字段中获取值.

The main fix is that you get the value from an <input> field with the .value property.

其余的更改是将输入的字符串映射到问题的更有效方法.

The rest of the change is a more efficient way to map a typed string to the question.

如果您的场景总是简单的序列号,那么您也可以使用数组查找:

If your scenarios are always simple sequential numbers, then you could use an array lookup too:

<script>

document.getElementById("clicker").onclick = function() {
    var scenario = document.getElementById('scenario').value; 
    var answers = [
        "How are you?",
        "whatevers",
        "i don't know",
        "today is your lucky day",
        "This is the worse case scenario"
    ];
    if (scenario) {
        var str = answers[+scenario - 1];
        if (str) {
            document.getElementById("answer").innerHTML = str;
        }
}

</script>

一般来说,如果您能找到一种方法将 switch 语句表示为数组查找或对象查找,您最终会得到更清晰、更小且更易于维护的代码.


In general, if you can find a way to express a switch statement as either an array lookup or an object lookup, you will end up with cleaner, smaller and easier to maintain code.