javascript 获取值 onchange

javascript get value onchange

我正在尝试获取 select 输入值以显示在 div onchange 中,但它似乎不起作用,我只是想知道是否有人可以提供帮助或知道为什么?

function getData(dropdown) {
  var values = dropdown.options[dropdown.selectedIndex].value;
  var pop = Game.currentGame.ui.options.servers.values.population;
  var servers = document.getElementsByClassName('hud-intro-guide')[0];
  servers.textContent = "Server " + pop + " population"
}
<select class="hud-intro-server" onchange="getData(this);">
  <optgroup label="asia servers">
    <option value="v8617903">asia #1 </option>
    <option value="v8617895">asia #2 </option>
    <option value="v8617899">asia #3 </option>
    <option value="v8617900">asia #4 </option>
    <option value="v8617898">asia #5 </option>
    <option value="v8617894">asia #6 </option>
    <option value="v8617901">asia #7 </option>
    <option value="v8617902">asia #8 </option>
    <option value="v8617897">asia #9 </option>
  </optgroup>
</select>

<div class="hud-intro-guide"> </div>

您不需要在 select 标签上添加更改事件。只需在 document.ready 函数中的 select 函数中添加 change 事件,如下所示:

$('#your select id').on('change', function() {  alert( this.value );});

 $('.your select class').on('change', function() {  alert( this.value );});
var pop = Game.currentGame.ui.options.servers.values.population;

应该是

var pop = Game.currentGame.ui.options.servers[values].population;

您的问题可能与您尝试使用变量 values 的方式有关。

  var pop = Game.currentGame.ui.options.servers.values.population;
                                                ^
                                                |
                                                +-- Here you're accessing the attribute values 
                                                    rather than getting the server related 
                                                    to the chosen option.

你真正想要的是:

function getData(dropdown) {
  var values = dropdown.options[dropdown.selectedIndex].value;
  var pop = Game.currentGame.ui.options.servers[values].population; 
                                                ^
                                                |
                                                +-- With this, you're getting the server.

  var servers = document.getElementsByClassName('hud-intro-guide')[0];
  servers.textContent = "Server " + pop + " population"
}