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

问题描述 投票:1回答:1

首先,我对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>
javascript html select switch-statement
1个回答
1
投票

由于您定义了带有参数的kentsReward(*parameter*)。在选择标记处调用时,您不会传递任何内容。尝试传递选择字段的当前值,例如<select name="behaviour" id="behaviour" onChange="kentsReward(this.value)">

© www.soinside.com 2019 - 2024. All rights reserved.