当前位置: 代码迷 >> JavaScript >> 在html中添加多个孩子,其中一个作为默认值
  详细解决方案

在html中添加多个孩子,其中一个作为默认值

热度:80   发布时间:2023-06-13 11:34:49.0

在查询 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一次并添加片段

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);

参考: :

  相关解决方案