select option 的问题总结

select 是列表型元素中的一个很重要的代表。总结下他的一些书写注意事项。

 1.关于innerHTML ,在ie下不支持innerHTML的形式添加option选项,firefox,chrome是支持的。

 2.添加option,使用 ele.options.add(option) ,但是这里的option 可以是new Option(text,value)的形式构造的,也可以是通过

原生的函数document.createElement函数创建的。此外add的方式不会覆盖以前的。option不能是html的形式。

 3.选定特定的一个option的方式 ele.value = option.value;反之,如果当前是特定的option的话,

那么ele的值一定就是option.value;

 4.获得选定的option的值还有另一个方式(我不太推荐)ele.options[ele.selectedIndex].value,这个尽管复杂一点,但是说明一个问题,

 即列表型元素的列表项有一个索引的概念。

附上我研究的code:

 1 <!DOCTYPE HTML>
 2 <html >
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html;charset=gb2312" />
 5     <title></title>
 6     
 7 </head>
 8 <body>
 9     <select name="test" id="test">
10     <option value="etcyby">hehe</option>
11     </select>
12     <script type="text/javascript">
13     function $(id){
14         return document.getElementById(id);
15     }
16     function render(){
17         for(var i = 0 ;i < 100;i++){
18             var ele = document.createElement('option');
19                 ele.text ='etcyby' + i;
20                 ele.value  = i;
21             $('test').options.add(ele);
22         }
23         $('test').value = '99'
24         //alert($('test').options[$('test').selectedIndex].value);
25     }
26     function render2(){
27         $('test').innerHTML = '<option value="etcyby">hehe</option>';
28     }
29     render();
30     </script>
31 </body>

32 </html> 

原文地址:https://www.cnblogs.com/yupeng/p/2010143.html