addEventListener如何更改下拉选定值Javascript?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (130)

我试图根据下拉框选择的值运行两个函数.

代码:

var activities = document.getElementById("stand");
activities.addEventListener("change", function() {

  if (activities.options[activities.selectedIndex].value == "stand1") {
    var footRight = new THREE.Mesh(new THREE.BoxGeometry(.040, 0.55, 0.05), wallMaterial);
    partitionLeft.add(footRight);
    footRight.position.set(-0.12, -0.11, 2);
  } else {
    var footRight = new THREE.Mesh(new THREE.BoxGeometry(.040, 0.55, 0.05), wallMaterial);
    partitionLeft.add(footRight);
    footRight.position.set(-4.12, -8.9, 6);
  }
});
<div id="door-stand">
  <label>Select the stand type:</label>
  <select id="stand">
    <option class="stand1" value="stand1"> Stand 1 </option>
    <option class="stand2" value="stand2"> Stand 2 </option>
  </select>
</div>

问题是,尽管下拉列表中的值不断变化,但上述任何函数都不会触发。

提问于
用户回答回答于

正如你所看到的,在删除了所有不必要的代码之后,这个简单的代码段可以像预期的那样工作:

const activities = document.getElementById('stand');

activities.addEventListener('change', (e) => {
  console.log(`e.target.value = ${ e.target.value }`);
  console.log(`activities.options[activities.selectedIndex].value = ${ activities.options[activities.selectedIndex].value }`);
});
<select id="stand">
  <option class="stand1" value="stand1">Stand 1</option>
  <option class="stand2" value="stand2">Stand 2</option>
</select>

扫码关注云+社区

领取腾讯云代金券