【问题标题】:Dynamically adding option values to a selectbox from an array从数组中将选项值动态添加到选择框
【发布时间】:2013-11-06 00:04:09
【问题描述】:

我需要你的帮助。

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

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

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>

即。

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])
}

【问题讨论】:

    标签: javascript


    【解决方案1】:

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

    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),只要您保持一致即可。

    【讨论】:

    • 工作就像一个魅力。谢谢:)
    【解决方案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('');
    

    【讨论】:

      【解决方案3】:

      这是另一种方法:

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

      这是工作代码:

      fiddle

      【讨论】:

        猜你喜欢
        • 2016-04-27
        • 2018-04-18
        • 2022-01-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-21
        • 2018-05-02
        相关资源
        最近更新 更多