javascript - 添加到选择元素的动态选项无法正确呈现
问题描述
我已阅读 SO 提供的所有类似问题,但没有人解决我的问题。
我有以下html:
<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<form action="" id="myForm">
<div class="input-field col s12 l6">
<select id="myselectid" name="myselectname">
</select>
</div>
<div class="col s12 l6">
<button id="" class="btn blue" type="submit"> submit</button>
</div>
</form>
我需要使用 JSON 文件的键“名称”的值填充 select 元素。
我的JSON
"resources": [
{
"name": "test.txt",
"format": "txt",
"size": 92502
},
{
"name": "mini-test.txt",
"format": "txt",
"size": 64855
}
]
我的
<script>
document.addEventListener('DOMContentLoaded', function() {
$.getJSON(myJSON, function(data){
var select = document.getElementById("myselectid");
$.each(data.resources, function(i, field){
select.add(new Option(field.name, field.name));
});
});
});
$(document).ready(function(){
$('.sidenav').sidenav();
$('select').formSelect();
});
</script>
我得到一个默认值为空的下拉菜单。通过单击箭头展开菜单,我只得到选项"test.txt"
。
奇怪的是,Firefox 检查器以灰色显示预期的 html
<select id="myselectid" name="myselectname" tabindex=-1>
<option value="test.txt">test.txt</option>
<option value="mini-test.txt">mini-test.txt</option>
</select>
到底是怎么回事?
任何帮助都非常受欢迎..
先感谢您
编辑:问题是由物化框架引起的。在向它添加选项之前,我正在初始化选择元素。查看我的答案以获取详细信息。
解决方案
多亏了 Materialize Gitter 频道的 Sean Doherty,这个问题已经得到解决。
出现问题是因为我在动态填充之前初始化了 M 选择元素。
以下是正确的
我的
<script>
document.addEventListener('DOMContentLoaded', function() {
$.getJSON(myJSON, function(data){
var select = document.getElementById("myselectid");
$.each(data.resources, function(i, field){
select.add(new Option(field.name, field.name));
});
// init select element after collecting the option values
M.FormSelect.init(document.querySelectorAll('select'));
});
});
$(document).ready(function(){
$('.sidenav').sidenav();
// do not init select here because the dyn population is not done yet
//$('select').formSelect();
});
</script>
推荐阅读
- r - 将两个模型的 ranef 图与 grid.arrange() 组合的问题
- pytest - 如何将 pytest 日志输出整理到控制台?
- assembly - 根据此表在 MIPS 中查找标签地址
- spring-boot - 使用带有 yaml 文件的 SpringDoc 托管 Swagger 文档
- ios - iOS 使用 Firebase FCM 向特定用户推送通知
- android - android MVVM架构中Layout Binding和Manual Binding(with observe)的比较
- arrays - 使用结构数组子集的 Swift 字典
- ruby-on-rails - 具有多个值的 Rails select_tag 仅发送第一个
- javascript - 如何在 React js 中将多个变量从一个功能组件传递到另一个?
- python - 安装了numpy,但是astropy说没有安装numpy