JS中select下拉列表选中的值

2017-09-01  本文已影响0人  Bennt

select 元素可创建单选或多选菜单,能够占据很小的区域,却包含很多的内容,在政府网站中使用率很高,今天就简单谈谈select这个元素。

1.基本属性
通常来说,我们用select元素来创建下拉列表,用option元素来定义列表中待选择的选项。一般来说,下来列表的第一个待选项为默认选项。

默认选中的方法,只需要在option元素添加 "selected = 'selected' " 即可:

<select>
      <option>值1</option>
      <option selected = 'selected'>值2</option>
      <option>值3</option>
</select>

2.动态创建select

var select = document.createElement('select');
select.id = 'mySel';
body.appendChild(select);

3.动态创建option

var mySel = document.getElementById('mySel');
mySel.add(new Option(text,value));

add() 方法用于向 <select> 添加一个 <option> 元素,add(option,before)。

参数 描述
option 要添加选项元素。必需是 option 或 optgroup元素
before 在选项数组的该元素之前增加新的元素。如果该参数是null,元素添加到选项数组的末尾。

4.删除option

//全部删除option
mySel.options.length = 0;
//删除指定索引的option
mySel.options.remove(i);    //i为任意索引值

5.获取选中的选项

 //当前选中的选项的索引
var index = mySel.selectedIndex;  
//获取选中的文本
mySel.options[index].text;   
//获取选中选项的value值
mySel.options[index].value;   

好了,读者可根据select的操作方法,可以尝试做省级联动。

上一篇 下一篇

猜你喜欢

热点阅读