addEventListener onchange下拉列表选择的值Javascript

时间:2018-06-25 23:54:37

标签: javascript html

我试图根据下拉框选择的值运行2个功能。

代码:

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>

问题仍然存在,尽管下拉列表中的值一直在变化,但上述任何功能都不会触发。

当下拉列表中的值更改时,我尝试打印一些内容;但是,什么都没有打印。


当我更改下拉列表中的值时出现控制台错误。仅在更改值时才会弹出控制台错误。这就是为什么我没有注意到的原因。它说

  

wallMaterial未定义

2 个答案:

答案 0 :(得分:3)

如您所见,删除所有不必要的代码后,此简单代码段按预期工作:

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>

这意味着您的代码中可能还有其他错误:

  • 也许有些错误:

    const activities = document.getElementById('stand');
    
    activities.addEventListener('change', (e) => {
      console.log('Change START');
      
      activities.nonexistentFunction();  
      
      console.log('Change END');
    });
    <select id="stand">
      <option class="stand1" value="stand1">Stand 1</option>
      <option class="stand2" value="stand2">Stand 2</option>
    </select>

  • 也许您还有其他change个监听器正在呼叫Event.stopImmediatePropagation()

    const activities = document.getElementById('stand');
    
    activities.addEventListener('change', (e) => {
      e.stopImmediatePropagation();
      
      console.log('Change 1');
    });
    
    activities.addEventListener('change', (e) => {  
      console.log('Change 2');
    });
    <select id="stand">
      <option class="stand1" value="stand1">Stand 1</option>
      <option class="stand2" value="stand2">Stand 2</option>
    </select>

答案 1 :(得分:0)

您可以使用this.value来访问回调函数中选定选项的值:

   document.getElementById('stand').onChange = function(){  
        console.log(this.value);
    });