本文介绍了带有输入文本的 Javascript switch 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<script>
document.getElementById("clicker").onclick = function () {
    var scenario = document.getElementById('scenario');
    switch (scenario) {
        case 1:
            document.getElementById("answer").innerHTML = "How are you?";
            break;
        case 2:
            document.getElementById("answer").innerHTML = "whatevers";
            break;
        case 3:
            document.getElementById("answer").innerHTML = "i don't know";
            break;
        case 4:
            document.getElementById("answer").innerHTML = "today is your lucky day";
            break;
        default:
            document.getElementById("answer").innerHTML = "This is the worst case scenario";
    }
}
</script>

<input type="text" id="scenario" />
<input type="submit" id="clicker" />
<p id="answer"></p>

所以在这里我试图基本上有一个文本字段,用户将在其中输入一些值根据该值,脚本将查看案例并确定在段落元素中输出什么.

So here i'm trying to basically have a text field where the user will type in some valuebased on that value, the script will then look at cases and determine what to output in the paragraph element.

请告知我应该如何更正此代码.

Please advise how i should correct this code.

推荐答案

我建议:

<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.

这篇关于带有输入文本的 Javascript switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 04:56