js進階 9-12 如何將數組的信息添加到下拉列表


js進階 9-12 如何將數組的信息添加到下拉列表

一、總結

一句話總結:創建出select的option,然后selectElement的add方法加進 selectElement 即可

 

1、創建出select的option的兩種方法:

new option() 和 createElement('option')

 

 

 

二、js進階 9-12 如何將數組的信息添加到下拉列表

1、案例說明:數組數據添加到下拉列表

  • 使用二維數組和下拉菜單相結合,實現多級聯動菜單

  • 使用createElement的方法

 

 

2、相關知識:Select 下拉列表

Select 對象集合
  • options[]返回包含下拉列表中的所有選項的一個數組
Select對象屬性
  • length返回下拉列表中的選項數目
  • multiple 設置或返回是否選擇多個項目。
  • selectedIndex 設置或返回下拉列表中被選項目的索引號。
  • size 設置或返回下拉列表中的可見行數。
  • id/name/disabled/form/tabIndex
Select 對象方法
  • add() 向下拉列表添加一個選項。

    語法:selectobject.add(option,before)

  • remove() 從下拉列表中刪除一個選項.

    語法: selectobject.remove(index)

  • blur()/focus()
Option 對象的屬性
  • defaultSelected 返回 selected屬性的默認值。
  • index 返回下拉列表中某個選項的索引位置。
  • Selected 設置或返回 selected 屬性的值。
  • text 設置或返回某個選項的純文本值。
  • disabled/form/id/value......

 

 

3、代碼

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>演示文檔</title>
 6 </head>
 7 <body>
 8     <form name="form1" action="">
 9         <select name="sel" size="3">
10         </select><br>
11         <input type="button" value="測試按鈕" onclick="addopt()">
12     </form>
13 <script>
14 var arr=new Array('數組元素1','數組元素2','數組元素3','數組元素4')
15 var counts=arr.length;
16     function addopt(){
17         for(var i=0;i<counts;i++){
18             // document.form1.sel.options[i]=new Option (arr[i],i)
19             var opt=document.createElement('option')
20             opt.text=arr[i]
21             opt.value=i;
22             document.form1.sel.add(opt,undefined)
23         }
24         var opt2=document.createElement('option')
25             opt2.text='opt2'
26             document.form1.sel.add(opt2,1)
27     }
28 </script>
29 </body>
30 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM