Javascript - innerHTML属性

nsa*_*x91 1 html javascript innerhtml

我正在使用innerHTML函数在HTML中动态创建一个下拉菜单,并使用某些参数填充它.这是我的代码:

for (i in categories) {
    var cat_name = i;
    var cats = categories[cat_name];

    P2_txt.innerHTML += cat_name;       

    if (cats.length > 2) {
        // Drop Down Menu Needed
        P2_txt.innerHTML += '<select>';

        for (var j = 0; j < cats.length; j++) {
            P2_txt.innerHTML += '<option>'+cats[j]+'</option>';
        }

        P2_txt.innerHTML += '</select>';
    }   
}
Run Code Online (Sandbox Code Playgroud)

但是,当我运行它时,会生成以下HTML代码:

<select></select>
<option>Value of cats[0]</option>
<option>Value of cats[1]</option>
<option>Value of cats[2]</option>
Run Code Online (Sandbox Code Playgroud)

而不是我想要的,这是:

<select>
    <option>Value of cats[0]</option>
    <option>Value of cats[1]</option>
    <option>Value of cats[2]</option>
</select>
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

I a*_*ica 7

当你修改innerHTML它时会立即解析为DOM ...所以你已经有效地添加了一个select元素,后面跟着一堆option元素超出了预期的层次结构.

所以,你要么:

  1. 构建整个组合框标记,然后将其添加到 innerHTML
  2. 使用DOM方法createElementappendChild等等,而不是丑陋的字符串连接.

var categories = {
    "Domestic": ["Tabby", "Siamese"],
    "Wild": ["Cougar", "Tiger", "Cheetah"]
  },
  cats,
  combo,
  frag = document.createDocumentFragment();

for (var category in categories) {

  cats = categories[category];

  frag.appendChild(document.createTextNode(category));

  combo = document.createElement("select");

  for (var i = 0, ln = cats.length; i < ln; i++) {
    combo.appendChild(document.createElement("option")).textContent = cats[i];
  }

  frag.appendChild(combo);
}

document.body.appendChild(frag);
Run Code Online (Sandbox Code Playgroud)