JS开关基于选定的选项

时间:2015-10-16 08:40:12

标签: javascript html


我尝试编写简单的JS开关,它将显示基于选择的内容,所以假设我将拥有带有4个div的html doc如果用户将选择选项一个div将显示等。

这是我制作的快速草稿,但它不起作用。你能帮我理解我在这里做错了什么吗?

HTML

  <legend>Selecting elements</legend>
          <p>
             <label>Select list</label>
             <select id = "myList">
               <option value = "1">one</option>
               <option value = "2">two</option>
               <option value = "3">three</option>
               <option value = "4">four</option>
             </select>
          </p>
       </fieldset>
       <p id ="demo"></p>


JS

function myfunction () {
        var text;
        var city = getElementById("myList").value;

        switch(city) {
            case "one":
            text ="test one";
            break;

            case "two":
            text ="test two";
            break;

            case "three":
            text ="test three";
            break;

            case "four":
            text = "test four";
            break;

            default:
            text = " ";
            }
            document.getElementById("demo").innerHTML = text;
            }

2 个答案:

答案 0 :(得分:1)

代码

的问题很少

&#13;
&#13;
function myfunction() {
  var text;
  var city = document.getElementById("myList").value; //need to use document.getElementById()

  switch (city) {
    //the select values are 1, 2, 3 not one, two etc
    case "1":
      text = "test one";
      break;

    case "2":
      text = "test two";
      break;

    case "3":
      text = "test three";
      break;

    case "4":
      text = "test four";
      break;

    default:
      text = " ";
  }
  document.getElementById("demo").innerHTML = text;
}
&#13;
<legend>Selecting elements</legend>
<p>
  <label>Select list</label>
  <!--Need to call myfunction on change of the select-->
  <select id="myList" onchange="myfunction()">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
    <option value="4">four</option>
  </select>
</p>
</fieldset>
<p id="demo"></p>
&#13;
&#13;
&#13;

如果您只想显示预定义的文字,那么

&#13;
&#13;
var mymap = {
  1: "test one",
  2: 'test two',
  3: 'test three',
  4: 'test four'
}

function myfunction() {
  var city = document.getElementById("myList").value; //need to use document.getElementById()
  var text = mymap[city] || ' ';
  document.getElementById("demo").innerHTML = text;
}
&#13;
<legend>Selecting elements</legend>
<p>
  <label>Select list</label>
  <!--Need to call myfunction on change of the select-->
  <select id="myList" onchange="myfunction()">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
    <option value="4">four</option>
  </select>
</p>
</fieldset>
<p id="demo"></p>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

onchange =“myfunction()”

添加此项以调用您的函数