DOM Select对象

 

   ---- 代表HTML表单中的一个下拉框

 

         <select>标签每出现一次,一个Select对象就会被创建

 

举例参考:

 

 

<select id="test">
   <option value="0">1000</option>
   <option value="1">2000</option>
   <option value="2">3000</option>
   <option value="3">4000</option>
</select>



 

 

Select对象属性

 

 

  • length    ------  返回下拉框列表的选项数目

document.getElementById('test').length; //4

     

 

  • multiple  -------设置或返回是否选择多个项目

  

<select id="test" multiple>
</select>

//或者用js去设置
document.getElementById('test').multiple = true;

 

 

Select对象集合

 

   ------options     返回包含下拉框列表中所有选项的一个数组

 

 

var el = document.getElementById('test');
var str ="";
for(var i=0;i<el.length;i++){
   //访问el.options这个[]
    str += el.options[i].text;
    str += ' '
}
console.log(str);   //1000 2000 3000 400 

 

 

 

Select对象方法

 

  • add   ---- 向下拉框添加一个选项

/*
@param option  必需 要添加的选项元素
@param before
*/
selectObj.add(option,before);

 

  举例:

 

 


var test  = document.getElementById('test');
var y = document.createElement('option');
y.text = '新建的选项';
try{
    test.add(y,null);
}catch(e){
    test.add(y);   //IE
}


 

 

 


  •  remove  -----从下拉框列表删除选项


/*
@index  必需。删除的选项的索引号
如果下标比0小或者大于或等于选项的数目,则忽略remove操作
*/
selectObj.remove(index);


   举例:



//删除选中的option
var test = document.getElementById('test');
test.remove(test.selectedIndex);

//删除最后一个
test.remove(test.length-1);