javaScript动态给下拉列表框添加选项

时间:2024-02-20 20:02:20

方式一:

 1 <html xmlns="http://www.w3.org/1999/xhtml">
 2 <head>
 3     <title></title>
 4     <script type="text/javascript">
 5         window.onload = function () {
 6             var sel = document.getElementById("selBirthday");
 7             for (var i = 0; i < 20; i++) {
 8                 var opt = document.createElement("option");
 9                 opt.innerHTML = i;
10                 opt.value = i;
11                 sel.appendChild(opt);
12             }
13         }
14     </script>
15 </head>
16 <body>
17     <select id="selBirthday">
18     </select>
19 </body>
20 </html>
动态给下拉列表框添加选项


方式二:

 1 <html xmlns="http://www.w3.org/1999/xhtml">
 2 <head>
 3     <title></title>
 4     <script type="text/javascript">
 5         window.onload = function () {
 6             var sel = document.getElementById("selBirthday");
 7             for (var i = 0; i < 20; i++) {
 8                 var opt = new Option(i, i); //第一个参数是选项显示的值,第二个是每个选项的value
 9                 sel.options.add(opt);
10             }
11         }
12     </script>
13 </head>
14 <body>
15     <select id="selBirthday">
16     </select>
17 </body>
18 </html>
动态给下拉列表框添加选项