layui动态添加下拉框组件,并且渲染数据
时间: 2024-04-24 14:03:47 浏览: 132
1. 首先引入layui组件库和jQuery库
```html
<!-- 引入layui组件库 -->
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/layui/2.5.6/css/layui.min.css" integrity="sha384-Bdk6U5D6umgKlLa5fWl5XZgI0ZUuV7Q2bKkOz7cO+VDfOMJ7CvPKaKjDhJzK9Zk1" crossorigin="anonymous">
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.5.6/layui.min.js" integrity="sha384-vd1YSOZrKwYh3zJbW8+OJzr4gOf4Z9AqKj8xv6JFy6g5Q5U5H6lKvJU5aZn/9Znt" crossorigin="anonymous"></script>
<!-- 引入jQuery库 -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha384-J6GCwI7a+Y7a5ssA7nL4p4YwcXnr3j+yLvTC7adK3Ri5A5V5diWk5jJvMvZb+aK9" crossorigin="anonymous"></script>
```
2. 在页面中添加一个空的下拉框组件
```html
<select id="select"></select>
```
3. 使用jQuery动态添加下拉框选项
```javascript
// 获取下拉框元素
var selectElem = $('#select');
// 模拟获取数据
var data = [
{id: 1, name: '选项一'},
{id: 2, name: '选项二'},
{id: 3, name: '选项三'},
];
// 遍历数据,动态添加选项
$.each(data, function(i, item){
var optionElem = $('<option></option>');
optionElem.val(item.id);
optionElem.text(item.name);
selectElem.append(optionElem);
});
// 使用layui组件渲染下拉框
layui.use(['form'], function(){
var form = layui.form;
form.render('select');
});
```
4. 完整代码
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>动态添加下拉框组件,并且渲染数据</title>
<!-- 引入layui组件库 -->
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/layui/2.5.6/css/layui.min.css" integrity="sha384-Bdk6U5D6umgKlLa5fWl5XZgI0ZUuV7Q2bKkOz7cO+VDfOMJ7CvPKaKjDhJzK9Zk1" crossorigin="anonymous">
<script src="https://cdn.bootcdn.net/ajax/libs/layui/2.5.6/layui.min.js" integrity="sha384-vd1YSOZrKwYh3zJbW8+OJzr4gOf4Z9AqKj8xv6JFy6g5Q5U5H6lKvJU5aZn/9Znt" crossorigin="anonymous"></script>
<!-- 引入jQuery库 -->
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha384-J6GCwI7a+Y7a5ssA7nL4p4YwcXnr3j+yLvTC7adK3Ri5A5V5diWk5jJvMvZb+aK9" crossorigin="anonymous"></script>
</head>
<body>
<!-- 空的下拉框组件 -->
<select id="select"></select>
<script>
// 获取下拉框元素
var selectElem = $('#select');
// 模拟获取数据
var data = [
{id: 1, name: '选项一'},
{id: 2, name: '选项二'},
{id: 3, name: '选项三'},
];
// 遍历数据,动态添加选项
$.each(data, function(i, item){
var optionElem = $('<option></option>');
optionElem.val(item.id);
optionElem.text(item.name);
selectElem.append(optionElem);
});
// 使用layui组件渲染下拉框
layui.use(['form'], function(){
var form = layui.form;
form.render('select');
});
</script>
</body>
</html>
```
阅读全文