问题描述
在查询 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);
}
1楼
selected 属性应设置为 true
您的代码在功能上是正确的。 但是在每个 for 循环中访问 dom 会导致性能问题。
相反,创建一个文档片段,将所有元素添加到片段中。 然后访问dom一次并添加片段
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);
参考: :