javascript - 在html中添加多个孩子,其中一个默认为
问题描述
在查询 frm localStorage 时,在 html 选择项中添加多个默认为一个的子项。
for (let i in jsonObj.records) {
let option = document.createElement("OPTION");
option.innerHTML = jsonObj.records[i].name;
option.value = jsonObj.records[i].unique;
if(jsonObj.records[i].assignee == data) {
option.selected = "select";
// is this the correct appproach
}
dropDown.appendChild(option);
}
解决方案
selected 属性应设置为 true
您的代码在功能上是正确的。但是在每个 for 循环中访问 dom 都会导致性能问题。
相反,创建一个文档片段,将所有元素添加到片段中。然后访问一次dom并添加fragment
var fragment = document.createDocumentFragment();
for (let i in jsonObj.records) {
let option = document.createElement("OPTION");
option.innerHTML = jsonObj.records[i].name;
option.value = jsonObj.records[i].unique;
if(jsonObj.records[i].assignee == data) {
option.selected = true;
// is this the correct appproach
}
fragment.appendChild(option);
}
dropDown.appendChild(fragment);
参考: https ://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment
推荐阅读
- apache-kafka - kafka 通过 flink 到 opentsdb:java.lang.NoClassDefFoundError:无法初始化类 org.apache.http.conn.ssl.SSLConnectionSocketFactory
- html - 面包屑将使用 uikit 放置在右上角的侧边按钮中
- spring - 无法从 Spring Okta (CRA SPA) 中检索委托人
- ruby-on-rails - 上传、处理和导出没有数据库的 CSV
- c# - 以可编程的方式为 seq 设置 Nlog
- java - 为什么我收到错误“java.lang.ClassNotFoundException”?
- reactjs - 反应警报问题
- windows - 在容器内运行基于 Windows 桌面 GUI 的应用程序
- sql - 在 pyspark 或 hive 中查找两个连续状态之间的持续时间
- php - 输出字符串的最后几个字符 - PHP / Yii