gpt4 book ai didi

javascript - 使用 Javascript DOM 操作从下拉列表值更改 HTML 元素

转载 作者:行者123 更新时间:2023-11-30 19:03:52 25 4
gpt4 key购买 nike

首先,我是 Javascript 的新手,如果这是一个简单的问题,我很抱歉。我的目标是在标记中显示我的 switch 语句的结果。现在,我只是想 console.log 它,但我似乎无法让它工作。我的困难似乎在于将下拉列表中的值存储在我可以在 switch 语句中使用的变量中。这是我尝试过的:

var behaviour = document.getElementById("behaviour");
var kentsBehaviour = behaviour.value;

console.log(kentsBehaviour)

//var h3 = document.getElementsByTagName("h3");

function kentsReward (kentsBehaviour) {
var prize;

switch (kentsBehaviour) {
case "Really good":
prize = "You get foot rubs!";
break;

case "Good":
prize = "You get an Oreo";
break;

case "Medium":
prize = "You get bread";
break;

case "Not so good":
prize = "You don't get anything";
break;

case "Greer":
prize = "You get pinches";
break;

default:
return "Tell me how you behaved today";
}

console.log( prize);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Kent's Rewards</title>
</head>
<body>
<h1>Please select your behaviour for today:</h1>
<select name="behaviour" id="behaviour" onChange="kentsReward()">
<option value="default">Select your behaviour</option>
<option value="Really good">Really good</option>
<option value="Good">Good</option>
<option value="Medium">Medium</option>
<option value="Not so good">Not so good</option>
<option value="Bad">Bad</option>
<option value="Greer">Greer</option>
</select>
<h2>Your reward is:</h2>
<h3></h3>
<script type="text/javascript" src="script.js"></script>
</body>
</html>

最佳答案

由于您定义了 kentsReward(*parameter*)需要一个参数。当它调用 select 标签时你没有传递任何东西。尝试传递选择字段的当前值,如 <select name="behaviour" id="behaviour" onChange="kentsReward(this.value)">

关于javascript - 使用 Javascript DOM 操作从下拉列表值更改 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59200016/

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