将数组连接到下拉列表;

时间:2013-12-19 09:50:05

标签: javascript arrays

我正在尝试将JSON对象数组关联到下拉列表,我不明白如何将数组初始化为下拉列表。我试过这个:

 function Save() {
    colors.nextColor.push({
    "name": document.getElementById("name").value,
    "rgb": document.getElementById("colordisplay").innerHTML,
    "opacity": document.getElementById("div").style.opacity
});

//pass the array into the dropdown list

var select = document.getElementById("selectColor");
    for (var i = 0; i < colors[i].length; i++) {
    var opt = colors[i];
    var el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;
    select.appendChild(el);

    console.log(colors);
}
}

我收到“Uncaught TypeError:无法读取未定义的属性'长度”这是项目jsbin.com/eXAligom/1

2 个答案:

答案 0 :(得分:0)

试试这个

var select = document.getElementById("selectColor");
for (var i = 0; i < colors[i].length; i++) {
    var opt = colors[i];
    var el = document.createElement("option");
    el.innerHTML = opt;
    el.value = opt;
    select.appendChild(el);
    console.log(colors);
}

答案 1 :(得分:0)

如果我理解正确,我会将Save()函数更改为:

function Save() {
colors.push({
    "name": document.getElementById("name").value,
    "rgb": document.getElementById("colordisplay").innerHTML,
    "opacity": document.getElementById("div").style.opacity
});
//pass the array into the dropdown list
var select = document.getElementById("selectColor");
    var opt = colors[colors.length-1],
        el = document.createElement("option"),
        desc = 'N: ' + (opt.name || 'unnamed') + ' RGB: ' + opt.rgb + ' O: ' + (opt.opacity || '0') ;
    el.innerHTML = desc;
    el.value = desc;
    select.appendChild(el);
    console.log(colors);}

这些变化几乎是不言自明的。