首先,我是Java语言的新手,所以很抱歉这是一个简单的问题。
我的目标是在标记中显示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 name="behaviour" id="behaviour" onChange="kentsReward(this.value)">

07-28 05:57