数组值未显示在下拉列表中

时间:2013-06-01 09:06:48

标签: javascript html arrays dom

我想在下拉列表中显示数组的元素。我在for循环中使用文档对象模型来执行此操作,但不断收到下拉列表为空的错误

Javascript代码

var str="-1,40,42,43,44,46,47,54,90,890,987,1235,4555,12434,122223,788998,789444,2147483647";
var n =new Array();
n = str.split(",");
alert(n);

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

HTML代码

<div id="rec1" name="rec1" style="display:none">
     <p>Select the Record number of the record you want to edit&approve&nbsp;&nbsp;&nbsp;
         <select id="rec"  name="rec" >
            <option value="def" selected="selected">Select choice</option>
         </select>
</div>

我得到的TypeError是“select is null”

1 个答案:

答案 0 :(得分:1)

您必须确保在加载DOM后Javascript正在执行。为了确保这一点,大多数人都会在window.onload函数中编写代码,如下所示:

<script>

window.onload = function(){
    var str = "-1,40,42,43,44,46,47,54,90,890,987,1235,4555,12434,122223,788998,789444,2147483647";
    var n = new Array();
    n = str.split(",");

    var select = document.getElementById("rec");
    for (i = 0; i < n.length; i++) {
        var opt = n[i];
        var el = document.createElement("option");
        el.textContent = opt;
        el.value = opt;
        select.appendChild(el);
    }
}
</script>

由于您的fiddle似乎工作正常,这可能是问题所在。否则,必须有一些其他代码干扰脚本。另请注意,我已删除小提琴上的样式display:none