使用javascript填充选择列表

时间:2013-08-09 22:07:02

标签: javascript html asp.net

我正在尝试使用JavaScript填充HTML选择列表。我相信我做得对,但我无法填写清单。该列表仍然是空的。我在这里缺少什么?

HTML:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script type="text/javascript" src="../../Scripts/app/Base.js"></script>
    <title>Index</title>
</head>

<body>
    <div>
    Select <select id = "MyList"></select>
    </div>
</body>
</html>

JS:

window.onload = function(){
    var select = document.getElementById("MyList");
    var options = ["1", "2", "3", "4", "5"];
    for (var i = 0; i < options.length; i++) {
        var opt = options[i];
        var el = document.createElement("option");
        el.textContent = opt;
        el.value = opt;
        select.appendChild(el);
    }
}

1 个答案:

答案 0 :(得分:6)

您的意思是window.onload吗?

小提琴:http://jsfiddle.net/5Jr8N/