我有一个ASP下拉列表,我需要加载数字1到20,默认情况下选择1。如何使用javascript做到这一点?我有一个示例代码,但下拉列表未加载。我想念什么吗?



<script>
    function quantitydropdown() {
        var ddl = document.getElementById('quantitydropdownid').getElementsByTagName("select")[0];

        for (var i = 1; i <= 100; i++) {
            var theOption = new Option;
            theOption.text = i;
            theOption.value = i;
            ddl.options[i] = theOption;
        }
    }
</script>

<select id="quantitydropdownid" onchange="javascript:quantitydropdown();" runat="server" style="width: 200px;"></select>

最佳答案

因此,当文档准备就绪时,我们将填充下拉列表:



// Set up event handler for when document is ready
window.addEventListener("DOMContentLoaded", function(){

  // Get reference to drop down
  var ddl = document.getElementById('quantitydropdownid');

  for (var i = 1; i < 21; i++) {
    var theOption = document.createElement("option");
    theOption.text = i;
    theOption.value = i;
    // If it is the first option, make it be selected
    i === 1 ? theOption.selected = "selected" :  "";
    ddl.options[i] = theOption;
  }
});

#quantitydropdownid { width:200px; }

<select id="quantitydropdownid" runat="server"></select>

09-25 15:24