javascript - 使用 JavaScript / jQuery 中数组中的选项递归填充选择字段
问题描述
我在 JavaScript 对象中有一些数据,需要递归地将其插入到选择字段中。问题是原始页面不是通过 AJAX 等加载,而是直接将整个数据加载到 DOM 中。因此,在页面加载之前,我们不知道会有多少子级别,因此需要递归算法
请考虑以下示例:
$(document).ready(function() {
var jsonData = {
"1": {
"uid": 1,
"value": "foo1",
"label": "FOO1",
"children": {
"2": {
"uid": 2,
"value": "foo1a",
"label": "FOO1a",
"parent": 1
},
"3": {
"uid": 3,
"value": "foo1b",
"label": "FOO1b",
"parent": 1
},
"4": {
"uid": 4,
"value": "foo1c",
"label": "FOO1c",
"parent": 1
}
}
},
"5": {
"uid": 5,
"value": "foo2",
"label": "FOO2",
"children": {
"6": {
"uid": 6,
"value": "foo2a",
"label": "FOO2a",
"parent": 5,
"children": {
"7": {
"uid": 7,
"value": "foo2a1a",
"label": "FOO2a1a",
"parent": 6,
"children": {
"8": {
"uid": 8,
"value": "foo2a1a1a",
"label": "FOO2a1a1a",
"parent": 7
}
}
}
}
}
}
}
};
// works only for the 1st select field for now...
// should fill the other fields with children options dependent on the selection in the 1st field
$(jsonData).each(function() {
$.each(jsonData, function(i) {
$('#singleselect-subject-1').append(
'<option value="' + jsonData[i].value + '" ' +
' data-uid="' + jsonData[i].uid + '">' + jsonData[i].label +
'</option>'
);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select optiondatasource="singleselect-subject-data" optiondatasourcefieldposition="1" id="singleselect-subject-1"></select>
<select optiondatasource="singleselect-subject-data" optiondatasourcefieldposition="1" id="singleselect-subject-2"></select>
<select optiondatasource="singleselect-subject-data" optiondatasourcefieldposition="1" id="singleselect-subject-3"></select>
你有一个想法,如何使 JavaScript 中的这种递归起作用?jQuery3 存在于项目中,因此可以(并且实际上应该)在可能且有意义的地方使用。谢谢!
解决方案
推荐阅读
- ios - Apns Delegate Never Fired Occurs 以及为什么我需要关闭我的网络和 wifi
- google-drive-api - 出现错误 - “远程服务器返回错误:(401)未经授权。” 使用 Google Drive API 请求文件时
- python - 如何在编码器解码器模型的训练期间填充序列
- java - JGit 使用 SSH 和密码认证
- sql - 基于 CASE Pivot 多行为单行多列
- list - Jinja2 无法正常显示列表合并
- python - 提高制作的圆形缩略图的图像质量
- vue.js - Vue组件:需要检查值
- java - 如何解决这个 ArrayList 问题?
- delphi - 在 Delphi 10.3 Firemonkey 中将 TPaintBox Canvas 的内容保存到位图(和/或文件)