JavaScript动态向Select下拉框添加数组数据的方法
作者:木棉时间:2026-10-29 14:06:15浏览:184
本文介绍如何使用JavaScript将数组数据动态添加到Select下拉菜单中。通过点击下拉框触发事件,实现数据的动态加载与内容替换,适用于前端本地化脚本操作。
JavaScript动态向Select下拉框添加数组数据的方法
本文详细介绍利用JavaScript将数组数据动态添加到Select下拉框的具体实现方法,供相关开发者参考使用。
该方案演示了如何将数组中的数据加载到Select下拉菜单中。当用户点击下拉框时,系统会动态加载数据;若需更换Select显示内容,只需直接替换数组中的数据即可。此方法适合前端开发者实现前台部分的本地化脚本操作。
具体运行效果如下图所示:

在线演示地址如下:
http://demo.jb51.net/js/2015/js-array-add-select-data-codes/
具体实现代码如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>将数组中的数据添加到下拉菜单中</title>
<style type="text/css">
<!--
.style1 {color: #FFFFFF}
-->
</style>
<script type="text/javascript">
var counts;
counts=0;
arr = new Array("JavaScript与ASP","JavaScript与JSP","JavaScript与ASP.NET","JavaScript与PHP");
counts=arr.length;
function Myselect(){
var i;
for (i=0;i < counts; i++) {
document.form1.sel.options[i] = new Option(arr[i],i);
}
}
</script>
</head>
<body>
<table width="280" height="160" border="0" align="center" cellpadding="5" cellspacing="0">
<tr>
<td height="34" align="center"><span class="style1" style="font-weight:bold ">将数组中的数据添加到下拉菜单中</span></td>
</tr>
<tr>
<td align="center" valign="top" bgcolor="#9ACCFF"><form name="form1">
<table width="235" height="69" border="0" align="center" cellpadding="0" cellspacing="0">
<tr>
<td height="21"><select name="sel" id="sel" onFocus="Myselect()">
</select></td>
</tr>
<tr>
<td height="120"> </td>
</tr>
</table>
</form></td>
</tr>
</table>
</body>
</html>
希望本文所述对大家的javascript程序设计有所帮助。
作者最新文章
JS合并多个数组的三种方法:concat、spread与flat
2026-11-05 17:39:45
JavaScript怎么准确判断数据类型:typeof、instanceof与Object.prototype.toString
2026-11-05 17:09:21
JS中将数组和对象混合组装为JSON字符串
2026-11-05 16:41:42
JS运算符优先级与结合性的区别是什么?
2026-11-05 13:22:02
JS Map怎么只遍历Key或Value
2026-11-05 13:00:36
