我究竟做错了什么?从下拉列表中获取选择。 Javascript

What am I doing wrong? Get selection from drop down list. Javascript

出于某种原因,我无法让它工作。我是 JS 的新手(通常对编码还很陌生),我已经研究了几个小时并在这里搜索。我看不出我的代码有什么问题。

我正在尝试从 select 选项列表中检索一个值。我想在另一个函数中使用该值。

这就是我正在尝试的,“Vocation”不会更改为值,即使我认为它应该更改。

<body>
<div class="wooh" style="width:200px;margin: 25px;">
  <select id="Vocation">
    <option value="0">Select Voc:</option>
    <option value="3.0">EK</option>
    <option value="1.4">RP</option>
    <option value="1.1">ED</option>
    <option value="1.1">MS</option>
  </select>
  
  <p id="result">Vocation</p>
</div>

<script>
// Edit your script here
function selection() {
  var x = document.getElementById("Vocation").value;
  document.getElementById("result").innerHTML = x;
}
</script>

我的最终“目标”是将值传递给此函数:

  var x = document.getElementById("level").value;
  var y = [value here]
  var z = 1600
  var a = 305000
  document.getElementById("result").innerHTML =  Math.ceil((z * Math.pow(y, x))/305000);

其中 y 应该是 selected 选项的值。我做错了什么?

您已经编写了代码,但没有指定何时应该编写代码 运行。你需要把你的函数变成一个“事件处理程序”。

<div class="wooh" style="width:200px;margin: 25px;">
  <select id="Vocation">
    <option value="0">Select Voc:</option>
    <option value="3.0">EK</option>
    <option value="1.4">RP</option>
    <option value="1.1">ED</option>
    <option value="1.1">MS</option>
  </select>
  
  <p id="result">Vocation</p>
</div>

<script>
  // You will be needing to refer to the result element more than once, so
  // just scan the document for it one time and cache the reference
  let result = document.getElementById("result");

  // Get a reference to the <select> element and bind a function to its change
  // event, which will trigger any time the select's value changes
  document.getElementById("Vocation").addEventListener("change", function() {
    // Because this function is bound to the select, when it is triggered
    // "this" will be an automatic reference to the select. 
    
    // Don't use .innerHTML when the string you are working with doesn't
    // contain any HTML because .innerHTML has security and performance
    // implications. For plain text, use .textContent
    result.textContent = this.value;
  });
</script>

了解有关事件和事件处理的更多信息here