0

I have a javascript array and I want to iterate through it to create the options in a <select> tag.

var sBoxContent = "categorieBox_content";
var oBoxContent = document.getElementById(sBoxContent);

oBoxContent.innerHTML += "<select name=\"clientCategories\">";

for(var i=0;i<oClientCategories.length;i++) {
        var categorieId = oClientCategories[i].id;
        var categorieLabel = oClientCategories[i].label;

        oBoxContent.innerHTML += "<option value=\"" + categorieId + "\">" + categorieLabel + "</option>";
 }

oBoxContent.innerHTML += "</select>";

The array is working properly since the option is displayed correctly but it appears outside the <select> tag.

HTML:

<td>
<select name="clientCategories"></select>
<option value="1">CategoryName</option>
</td>
4

3 回答 3

3

因为innerHTML总是试图创建有效的语法,

oBoxContent.innerHTML += "<select name=\"clientCategories\">"; 

实际上创建了这个 DOM 片段:

<select name="clientCategories"></select>

因此,您需要先组装您的 HTML 字符串,然后再将其分配给innerHTML

var sBoxContent = "categorieBox_content";
var oBoxContent = document.getElementById(sBoxContent);
var myHTML = "";


myHTML += "<select name=\"clientCategories\">";

for(var i=0;i<oClientCategories.length;i++) {
        var categorieId = oClientCategories[i].id;
        var categorieLabel = oClientCategories[i].label;

        myHTML += "<option value=\"" + categorieId + "\">" + categorieLabel + "</option>";
 }

myHTML += "</select>";
oBoxContent.innerHTML += myHTML;
于 2013-10-03T18:43:55.170 回答
1

innerHTML很奇怪,不像字符串那样工作。您传入的 HTML 已被解析,因此您传入的初始 HTML<select>会自动关闭。

相反,将其构建为一个字符串并innerHTML在事后使用。

var oBoxContentHTML = "<select name='clientCategories'>";
// etc.
oBoxContent.innerHTML += oBoxContentHTML;
于 2013-10-03T18:43:26.240 回答
0

我会使用 document.createElement() 而不仅仅是弄乱 HTML 字符串。

var oClientCategories = [{id: 1, label:"one"},{id: 2, label: "two"},{id: 3, label: "three"}];
var selectBox = document.createElement("select");

for(var i=0;i<oClientCategories.length;i++){
    var elem = oClientCategories[i];
    var addedOption = document.createElement("option");
    addedOption.value = elem.id;
    addedOption.innerHTML = elem.label;
    selectBox.appendChild(addedOption);
}

var cont = document.getElementById("categorieBox_content");
cont.appendChild(selectBox);

工作jsfiddle:http: //jsfiddle.net/V3fjx/

于 2013-10-03T18:52:37.560 回答