JavaScript 动态生成select下拉菜单
JavaScript 动态生成select下拉菜单属于前端实例代码,有关更多实例代码大家可以查看。
在实际应用中,可能需要动态生成select下拉菜单,本章节通过代码实例介绍一下如何实现此功能。
代码如下:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <meta name="author" content="http://www.pipipi.net/" /> <title>前端教程网</title> <script type="text/javascript"> function setFun(){ var id = new Array(1,2,3); var value = new Array("JavaScript专区","jQuery专区","实例教程"); var select = document.getElementById("area"); select.length = 1; select.options[0].selected = true; for(var x = 0;x<id.length;x++){ var option = document.createElement("option"); option.setAttribute("value",id[x]); option.appendChild(document.createTextNode(value[x])); select.appendChild(option); } } window.onload=function(){ setFun() } </script> </head> <body> <form> <select name="area" id="area"> <option value="0">--选择版块--</option> </select> </form> </body> </html>
可以动态生成select下拉菜单,下面简单介绍一下它的实现过程。
代码注释:
(1).function setFun(){},生成select下拉函数。
(2).var id = new Array(1,2,3),声明一个数组并初始化,数组值是option项的value值。
(3).var value = new Array("javascript专区","jQuery专区","实例教程"),声明一个数组并初始化,此数组的值option的文本内容。
(4).var select = document.getElementById("area"),获取select对象。
(5).select.length = 1,将select下拉菜单的length属性值设置为1,也就是说只能有一项可以被选中。
(6).select.options[0].selected = true,将第一个option设置为被选项。
(7).for(var x = 0;x<id.length;x++){},使用for循环遍历id数组。
(8).var option = document.createElement("option"),创建option对象。
(9).option.setAttribute("value",id[x]),将option的value属性值设置为数组的对应项。
(10).option.appendChild(document.createTextNode(value[x])),为option项添加文本节点,也就是<option>和</option>之间的文本。
(11).select.appendChild(option),为select下拉菜单添加option项。
二.相关阅读:
(1).document.getElementById参阅document.getElementById()一章节。
(2).document.createElement参阅document.createElement()一章节。
(3).for循环参阅JavaScript for 循环语句一章节。
(4).setAttribute参阅JavaScript setAttribute()一章节。
(5).appendChild参阅JavaScript appendChild()一章节。
JavaScript 动态生成select下拉菜单,这样的场景在实际项目中还是用的比较多的,关于JavaScript 动态生成select下拉菜单就介绍到这了。