【译文】JavaScript如何制作下拉列表

 JavaScript下拉列表   原文链接

下拉列表包含一个文本列表,网站用户可以从中进行选择。

HTML 选择项

源码

<html>
  <body>
    <select id="days">
      <option value="1">Monday</option>
      <option value="2">Tuesday</option>
      <option value="3">Wednesday</option>
      <option value="4">Thursday</option>
      <option value="5">Friday</option>
    </select>
  </body>
</html>

用JavaScript获得选择的值


源码

<html>
  <head>
    <script>
      function getDay() {
       var eID = document.getElementById("days");
        var dayVal = eID.options[eID.selectedIndex].value;
        var daytxt = eID.options[eID.selectedIndex].text;
        alert("Selected Day is " + daytxt + ", Value " + dayVal);
      }
    </script>
  </head>
  <body>
    <select id="days">
      <option value="1">Monday</option>
      <option value="2">Tuesday</option>
      <option value="3">Wednesday</option>
      <option value="4">Thursday</option>
      <option value="5">Friday</option>
    </select>
    <br><br>
    <button onclick="getDay()">Select Day</button>
  </body>
</html>

JavaScript 改变事件


源码

 
<html>
  <head>
    <script>
      function getDay() {
       var eID = document.getElementById("days");
        var dayVal = eID.options[eID.selectedIndex].value;
        var daytxt = eID.options[eID.selectedIndex].text;
        alert("Selected Day is " + daytxt + ", Value " + dayVal);
      }
    </script>
  </head>
  <body>
    <select id="days" onchange="getDay()">
      <option value="1">Monday</option>
      <option value="2">Tuesday</option>
      <option value="3">Wednesday</option>
      <option value="4">Thursday</option>
      <option value="5">Friday</option>
    </select>
  </body>
</html>



此条目发表在博客, 服务器, 程序开发, 计算机安全分类目录,贴了, , , , , 标签。将固定链接加入收藏夹。