gpt4 book ai didi

javascript - 访问 SELECT 元素和数组元素

转载 作者:行者123 更新时间:2023-12-03 07:47:36 25 4
gpt4 key购买 nike

我正在尝试创建一个基于电视节目的随机报价生成器。用户选择节目并点击“提交”按钮后,程序应根据所选电视剧显示随机引用。所有引号都位于其数组中。

我的代码如下。您能帮我理解为什么它不起作用以及如何修复它吗?

<!DOCTYPE html>
<html>
<body>

<h3>A demonstration of how to access a SELECT element</h3>

<select id="mySelect" size="2">
<option value="1">Suits</option>
<option value="2">Supernatural</option>
</select>

<p>Click the button to select the show and display a random quote.</p>

<button onclick="myFunction();">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
var suits = new Array("Specter is fat", "Ross is fat", "Pearsonis fat", "Litt is fat", "Zane is fat");
var supernatural = new Array("Dean is fat", "Sam is fat", "Castiel is fat");
var x = document.getElementById("mySelect").value;
switch (x) {
case 1:
var quote = suits[Math.floor(Math.random()*suits.length)];
document.getElementById("demo").innerHTML = quote;
break;
case 2:
var quote = supernatural[Math.floor(Math.random()*supernatural.length)];
document.getElementById("demo").innerHTML = quote;
break;
};
}
</script>

</body>
</html>

最佳答案

x 值作为字符串传入,但您的 JavaScript switch 正在寻找整数。如果您使用字符串,它应该按预期工作:

switch (x) {
case "1":
// stuff
case "2":
// stuff
}

关于javascript - 访问 SELECT 元素和数组元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35136993/

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