1

我需要你的帮助。

我在下面有以下函数,它从数组中读取数据,然后动态地将选项值添加到选择框。

有没有办法修改数组,以便我可以指定要添加的文本和选项值?

ABC,"testing"
DEF,"the system"
GHI,"further testing"
JKL,"desired results"

所以选择框现在类似于以下内容:

<select>
<option value="testing">ABC</option>
<option value="the system">DEF</option>
<option value="further testing">GHI</option>
<option value="desired results">JKL</option>
</select>

IE。

var y = [
"ABC",
"DEF",
"GHI",
"JKL"
]
for (var i = 0; i < y.length; i++ ){
    document.getElementById('select1').options[i]=new Option(y[i], y[i])
}
4

3 回答 3

2

试试这个:

var arr = [],
    key,
    options = {
        'value1': 'text1',
        'value2': 'text2',
        'value3': 'text3'
    };

for(key in options) {
    if(options.hasOwnProperty(key)) {
        arr.push(['<option value="', key, '">', options[key], '</option>'].join(''));
    }
}
document.getElementById('select1').innerHTML = arr.join('');
于 2013-11-05T15:51:39.747 回答
2

您需要将字符串数组更改为对象数组:

var y = [
    {toDisplay: "ABC", value: "testing"},
    {toDisplay: "DEF", value: "the system"},
    {toDisplay: "GHI", value: "further testing"},
    {toDisplay: "JKL", value: "desired results"}
];

for (var i = 0; i < y.length; i++) {
    document.getElementById('select1').options[i] = new Option(y[i].toDisplay, y[i].value);
}

当然,您可以随心所欲地调用对象中的参数(例如,text而不是toDisplay),只要您保持一致即可。

于 2013-11-05T15:51:58.307 回答
0

这是另一种方法:

function populateOption(name, value){

    select = document.getElementById('selectbox');


    var opt = document.createElement('option');
    opt.value = value;
    opt.innerHTML = name;
    select.appendChild(opt);


}

text = {'ABC' : "testing",
        'DEF':"the system", 
        'GHI':"further testing",
        'JKL':"desired results"}
for(var key in text){
    populateOption(key, text[key]);
}

这是工作代码:

小提琴

于 2013-11-05T16:04:09.150 回答