我的脚本在 Edge 中返回Microsoft未定义的错误

My script is returning an undefined error in Microsoft Edge

本文关键字:Microsoft 未定义 错误 返回 脚本 Edge 我的      更新时间:2023-09-26

这是JS和HTML代码:

function dateChange(){
  var e = document.getElementById("trainingtype");
  var str = e.options[e.selectedIndex].value;
  var val = str;
  if (val == "1"){
    var x = document.getElementsByClassName("class1");
    for(i=0; i<x.length; i++) {
      x[i].style.display = "block";
    }
    var x = document.getElementsByClassName("class2");
    for(i=0; i<x.length; i++) {
      x[i].style.display = "none";
    }
    var x = document.getElementsByClassName("class3");
    for(i=0; i<x.length; i++) {
      x[i].style.display = "none";
    }
    document.getElementById("datepicker").value="Select Date and Place";
  } else {
    //another If else statement
  }
}
<select name="item_name" id="trainingtype" onChange="dateChange()">
  <option selected>Select training type</option>
  <option value="Bike">Bike Riding</option>
  <option value="Bucket">Bucket Washing</option>
  <option value="Shoe">Shoe Tying</option>	
</select>
<select name="datepicker" id="datepicker" onChange="amountChange(value)">
  <option>Select Date and Place</option>
  <option class="class1" value="1">1</option>
  <option class="class2" value="2">2</option>
  <option class="class3" value="3">3</option>
</select>

此代码在Chrome,Safari和Firefox中完美运行,但在Microsoft Edge中不起作用。在控制台中,我收到错误:SCRIPT5009: 'value' is undefined

我该如何解决这个问题?

以下 JavaScript 行不会调用您期望的元素:

var e = document.getElementById("trainingtype");

这是调用#trainingtype元素,即:

<select name="item_name" id="trainingtype" onChange="dateChange()">
    <option selected>Select training type</option>
    <option value="Bike">Bike Riding</option>
    <option value="Bucket">Bucket Washing</option>
    <option value="Shoe">Shoe Tying</option>    
</select>

然后你继续测试vlaue:

var str = e.options[e.selectedIndex].value;
var val = str;
if (val == "1") {

但是,1 与选项列表中的任何值都不相似。原来的选项列表已被替换,但它们不是数字。它们是单词/短语。

相反,您似乎打算调用#datepicker(其值为 123)。否则,您可能无意中在第一个选项列表中使用了错误的值类型。