如何使用数组字段设置select元素的.selectedIndex?

时间:2014-04-02 20:17:40

标签: javascript selectedindex

我的脚本似乎做了我需要的操作,除了将所选选项标记为“已选择”或“已选择=已选择”。

注意:themeInfo中的一个对象将[4]设置为“selected”

    <script type='text/javascript'>
    var themeInfo = [
        ['Default', 'Default Template', 'Default.png', '&template=Default', ''],
        ['Desert', 'The Desert', 'Desert.png', '&template=Desert', 'selected'],
        ['Red', 'Big Red', 'Red.png', '&template=Red', '']
    ];
    window.onload = function(){

        var sel1O = document.getElementById('sel1');

        var themeList = document.getElementById('sel1'); //
        var selectedTheme = themeList.options[themeList.selectedIndex].value; //

        for(i=0; i<themeInfo.length; i++){
            sel1O.options[sel1O.options.length] = new Option(themeInfo[i][0], themeInfo[i][0], false, themeInfo[i][4] == 'selected');

                /* Need to mark option selected -DOESN'T WORK */
                //if (themeInfo[i][4] == 'selected') { //
                //    selection.selectedIndex = i; //
                //} //

        }
    }
    </script>


    <form id='skinselectorform' action='home.php' method='POST'>
            <select name='template' id='sel1'>
                <option>Select below...</option>
            </select>
            <input type='submit' class='button' value='GO'>
    </form>

2 个答案:

答案 0 :(得分:0)

您应该设置new Option()的选定参数,而不是selectedIndex

var themeInfo = [
  ['Default', 'Default Template', 'Default.png', '&template=Default', ''],
  ['Desert',  'The Desert',       'Desert.png',  '&template=Desert',  'selected'],
  ['Red',     'Big Red',          'Red.png',     '&template=Red',     '']
];

window.onload = function () {
    var sel1O         = document.getElementById('sel1');
    var themeList     = document.getElementById('sel1');

    for (i = 0; i < themeInfo.length; i++) {
      var selected = themeInfo[i][4] == 'selected';
      var option = new Option(themeInfo[i][0], themeInfo[i][0], false, selected);
      sel1O.options[sel1O.options.length] = option
    }
}

FIDDLE

答案 1 :(得分:0)

该行

selection.selectedIndex = i;

指的是未声明的变量。你想参考sel1O

sel1O.selectedIndex = i;

此外,之后休息会让你摆脱for循环,这可能不是你想要的行为。