首页 > 解决方案 > 在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);
}

标签: javascript

解决方案


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


推荐阅读