我正在尝试在循环中使用下拉菜单的选项值,但出现未捕获的错误,在filter1中所有未定义。

function filter1() {
    var x = document.getElementById("filter1").value;
    switch(x) {
        case all:
        getElementsByClassName("1").style.display="none";
        break;
    }
    console.log(x);
}


HTML:

 <select id="filter1" name="country" onchange="filter1()">
          <option value="all">All countries</option>
 </select>

最佳答案

您缺少在quotes中分配字符串的case 'all',并增加一个选项然后仅执行更改功能

更改document.getElementsByClassName("1")[0]而不是getElementsByClassName("1")因为类名是多重选择器



function filter1() {
  var x = document.getElementById("filter1").value;
  switch (x) {
    case 'all':
     console.log('work')
      //document.getElementsByClassName("1")[0].style.display = "none";
      break;
  }
  console.log(x);
}

<select id="filter1" name="country" onchange="filter1()">
          <option value="all">All countries</option>
          <option value="one">All one</option>
 </select>

07-24 17:35