gpt4 book ai didi

带有输入文本的 Javascript switch 语句

转载 作者:行者123 更新时间:2023-12-02 18:04:51 24 4
gpt4 key购买 nike

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

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

请告诉我应该如何更正此代码。

最佳答案

我建议这样做:

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

主要修复是从 <input> 获取值字段为 .value属性。

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

<小时/>

如果您的场景始终是简单的连续数字,那么您也可以使用数组查找:

<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 语句表达为数组查找或对象查找,您最终将得到更干净、更小且更易于维护的代码。

关于带有输入文本的 Javascript switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20184744/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com