【问题标题】:Load asp dropdown list with numbers 1 - 20加载带有数字 1 - 20 的 asp 下拉列表
【发布时间】:2017-04-18 20:53:52
【问题描述】:

我有一个名为 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>
&lt;select id="quantitydropdownid" onchange="javascript:quantitydropdown();" runat="server" style="width: 200px;"&gt;&lt;/select&gt;

【问题讨论】:

标签: javascript html asp.net


【解决方案1】:

所以,当文档准备好时,我们填充下拉列表:

// 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; }
&lt;select id="quantitydropdownid" runat="server"&gt;&lt;/select&gt;

【讨论】:

  • 我正在 fiddler 中尝试此代码,但下拉菜单未加载
【解决方案2】:
Please try with this code
-----------------------------------------

JS Code
----------------

$(document).ready(function(){
   quantitydropdown();
})

function quantitydropdown()
{
  for (var i = 1; i <= 20; i++) 
  {
    $("#quantitydropdownid").append( $("<option></option>")
                                    .attr("value", i)
                                    .text(i)
                                   );
   }
}

Css Code
-----------

#quantitydropdownid { width:200px; }

HTML Code
-----------

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

【讨论】:

  • 该问题未使用 JQuery 标记,但您的答案使用它。
  • 你是对的,但是我认为 jQuery 是 JavaScript 的包装器。所以我们可以根据需要使用。
  • 呃,没有。这不是它的工作方式。 JQuery 是一个 JavaScript 库,需要您引用并下载它才能使用它。这会导致用户用于访问您的页面的额外带宽。许多人/组织不能只添加一个库。而且,JQuery 可以做的任何事情都可以用直接的 JavaScript 来完成。这就是我们查看发布问题的标签的原因。如果用户想要一个 JQuery 答案,他们会以这种方式标记问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-17
  • 2013-01-20
  • 1970-01-01
  • 2016-07-02
相关资源
最近更新 更多