Javascript代码不会将选项放入选择框

时间:2011-06-13 22:53:38

标签: javascript html

我已经编写了一些应该将选项放入选择框的javascript代码。选择框的代码如下:

<select id="dayOfTheWeek" name="dayOfTheWeek"></select>

在我的javascript编码中,我有一个名为populateDays的方法,它应该用7个选项填充选择框 - 一个星期的每一天。它的代码如下:

function populateDays() {
var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
var dayOfWeek = document.getElementById("dayOfTheWeek");
var today = (new Date()).getDay();

for (var i = 0; i < days.length; i++) {
    var length = dayOfWeek.options.length;
    dayOfWeek.add(new Option(days[i], i), length);
}
dayOfWeek.selectedIndex = today;
}

稍后在脚本中我调用了这个方法。我知道浏览器加载时浏览器会运行javascript代码,因为我在populateDays方法中放了一个alert()语句,它出现在我加载页面的时候。

populateDays();

出于某种原因,当我加载页面时,选择框完全为空。为什么populateDays()方法没有加载带有选项的选择框?

3 个答案:

答案 0 :(得分:1)

我在IE8中遇到了与新选项有关的问题 - 它在其他所有浏览器中都有效。我最终用以下内容替换它,它在任何地方都有效,

selectBox.append("<option value=\"" + value + "\">" + text + "</option>");

答案 1 :(得分:1)

嗯,它应该有效just fine。如果没有:

方法2(jsFiddle example) - innerHTML

function populateDays() {
  var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
  var dayOfWeek = document.getElementById("dayOfTheWeek");
  var today = (new Date()).getDay();
  var options = "";

  for (var i = 0; i < days.length; i++) {
    options += '<option value="' + days[i] + '">' + days[i] + '</option>'
  }

  dayOfWeek.innerHTML = options;
  dayOfWeek.selectedIndex = today;
}

方法3 - 以编程方式创建元素

function populateDays() {
  var days = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
  var dayOfWeek = document.getElementById("dayOfTheWeek");
  var today = (new Date()).getDay();

  for (var i = 0; i < days.length; i++) {
    var option = document.createElement("option");
    option.value = days[i];
    var optionText = document.createTextNode(days[i]);
    option.appendChild(optionText);
    dayOfWeek.appendChild(option);
  }

  dayOfWeek.selectedIndex = today;
}

答案 2 :(得分:1)

听起来像brymck已经得到了这个。 在打开页面时我遇到了问题。所以这可能对某人有所帮助:

我认为javascipt是​​在选择器进入之前加载的。我将我的代码放在一个jquery文档就绪块中然后一切都开始工作了。

身体:

<select id="selector1" >
        </select>

这是我放在头部标签中的js:

var optionArr = ["option1", "option2", "option3", "option4"];

$(document).ready(function(){

    //add array of csv file names to selector element
    var sel = document.getElementById("selector1");

    for(i=0; i < csvFilesArr.length; i++){
        //opt += "<option>" + optionArr[i] + "</option>"
        var option = document.createElement("option");
        option.text = optionArr[i];
        sel.add(option);
    }

});