【问题标题】:JavaScript - populate drop down list with arrayJavaScript - 用数组填充下拉列表
【发布时间】:2012-04-11 07:28:46
【问题描述】:

我在脚本中声明了一个数组:

var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");

我有一个包含下拉菜单的表单:

<form id="myForm">
  <select id="selectNumber">
    <option>Choose a number</option>
  </select>
</form>

使用 Javascript,我将如何使用数组值填充下拉菜单的其余部分?这样选项将是“选择一个数字”、“1”、“2”、“3”、“4”、“5”。 . . . . “N”?

【问题讨论】:

  • 请发布您的尝试以及您收到的任何错误消息。谢谢。

标签: javascript arrays


【解决方案1】:

您需要遍历数组元素,为每个元素创建一个新的 DOM 节点并将其附加到您的对象:

var select = document.getElementById("selectNumber");
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);
}
<select id="selectNumber">
    <option>Choose a number</option>
</select>

【讨论】:

  • 我遇到了一个错误textContent &amp; value are not a function,解决方案是 cast 选择这样的字符串:el.textContent = String(opt); el.value = String(opt); 这是 opt的情况> 不是 字符串
  • @AbdallahOkasha 这没有意义。如果您尝试像这样使用el.textContent,则会发生该错误:el.textContent(opt)。如果您像在我的示例中那样使用它,那么它是否是 number 无关紧要,浏览器会将其转换为字符串。
  • 感谢您的关心 .. 实际上,我尝试写 el.textContent = arr[i]el.value = arr[i] 并收到错误消息:value, texttextContent 不是函数
  • @AbdallahOkasha 您能否在jsfiddle.net 之类的内容上重现此错误的最小示例并分享链接?
  • 这是本例中的 jsfiddle sn-p @alex .text 函数在不解析为字符串的情况下运行良好,但是在我的代码中它给了我一个错误,我实际上正在使用类似的字符串数组(每个都包含空格)。 jsfiddle.net/okasha/h1jt3yz1/2
【解决方案2】:

你也可以用 jQuery 来做:

var options = ["1", "2", "3", "4", "5"];
$('#select').empty();
$.each(options, function(i, p) {
    $('#select').append($('<option></option>').val(p).html(p));
});

【讨论】:

    【解决方案3】:

    我使用了Alex Turpinsolution 并进行了如下所述的小幅修正:

    var select = document.getElementById("selectNumber"); 
    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.text = opt;
        el.value = opt;
    
        select.add(el);
    }​
    

    更正,因为 appendChild() 函数会在 DOM 准备时加载。所以它不适用于旧的(8 或更小)IE 版本。因此,通过更正,它可以正常工作。

    关于the differences between add() and appendChild()的一些说明。

    【讨论】:

      【解决方案4】:

      我发现这也有效...

      var select = document.getElementById("selectNumber"); 
      var options = ["1", "2", "3", "4", "5"]; 
      
      // Optional: Clear all existing options first:
      select.innerHTML = "";
      // Populate list with options:
      for(var i = 0; i < options.length; i++) {
          var opt = options[i];
          select.innerHTML += "<option value=\"" + opt + "\">" + opt + "</option>";
      }
      

      【讨论】:

        【解决方案5】:

        您将首先从 DOM 中获取下拉元素,然后循环遍历数组,并将每个元素作为新选项添加​​到下拉列表中,如下所示:

        var myArray = new Array("1", "2", "3", "4", "5");
        
        
        // Get dropdown element from DOM
        var dropdown = document.getElementById("selectNumber");
        
        // Loop through the array
        for (var i = 0; i < myArray.length; ++i) {
            // Append the element to the end of Array list
            dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
        }
        <form id="myForm">
          <select id="selectNumber">
            <option>Choose a number</option>
          </select>
        </form>

        这假设您没有使用 JQuery,并且您只有基本的 DOM API 可以使用。

        【讨论】:

        • 注意,我在复制粘贴这段代码时遇到了这个问题:stackoverflow.com/questions/4404526/…
        • @NielsBrinch - 不要直接从 JSFiddle 复制和粘贴。 :)
        • 我实际上是从 Stackovervflow 复制粘贴的,而不是小提琴 - 但也许是 stackoverflow 作者从他自己的小提琴复制粘贴并且复制粘贴被继承了! :)
        • @NielsBrinch - 错误是什么?是“下拉列表未定义”吗?
        • 不,它正是我链接的那个。 webkit 中的“意外令牌非法”。
        【解决方案6】:

        这样的事情应该可以工作:

        var dropdown = document.getElementById("dropdown1");
        if (dropdown) {
            for (var i=0; i < month.length;++i){    
                addOption(dropdown, month[i], month[i]);
            }
        }
        
        addOption = function(selectbox, text, value) {
            var optn = document.createElement("OPTION");
            optn.text = text;
            optn.value = value;
            selectbox.options.add(optn);  
        }
        

        更多详情可以参考这篇文章:
        http://www.plus2net.com/javascript_tutorial/list-adding.php

        【讨论】:

          【解决方案7】:
          ["1","2","3","4"].forEach( function(item) { 
             const optionObj = document.createElement("option");
             optionObj.textContent = item;
             document.getElementById("myselect").appendChild(optionObj);
          });
          

          【讨论】:

            【解决方案8】:

            这是我的答案:

            var options = ["1", "2", "3", "4", "5"];
            for(m = 0 ; m <= options.length-1; m++){
               var opt= document.createElement("OPTION");
               opt.text = options[m];
               opt.value = (m+1);
               if(options[m] == "5"){
                opt.selected = true;}
            document.getElementById("selectNum").options.add(opt);}
            

            【讨论】:

            • 这是一个代码唯一的答案。请添加一些解释您的代码在做什么。
            【解决方案9】:

            如果你正在使用 React 和 JSX,你可以使用 map 函数。这样就不需要手动添加 DOM 节点了。

            const numsarray = [1, 2, 3, 4, 5];
            

            您可以将其映射到您的&lt;options&gt; 标记中(在&lt;select&gt; 内)

            <select>
              {numsarray.map((num) => (
                <option>{numsarray}</option>
              ))}
            </select>
            

            【讨论】:

              【解决方案10】:
              var test = document.getElementById("TestOption");
              var arr = ["A","B","C","D"];  
              //remove options if necessary
              for(var i=test.options.length- 1;i>= 0;i--) {test.remove(i);}        
              //add new options
              for(i in arr) {test.add(new Option(arr[i],i));}
              

              【讨论】:

                【解决方案11】:
                <form id="myForm">
                <select id="selectNumber">
                    <option>Choose a number</option>
                    <script>
                        var myArray = new Array("1", "2", "3", "4", "5" . . . . . "N");
                        for(i=0; i<myArray.length; i++) {  
                            document.write('<option value="' + myArray[i] +'">' + myArray[i] + '</option>');
                        }
                    </script>
                </select>
                </form>
                

                【讨论】:

                  【解决方案12】:

                  简单易调试的jQuery解决方案:

                  <form id="myForm">
                    <select id="selectNumber">
                      <option>Choose a number</option>
                    </select>
                  </form>
                  
                  <script>
                    var myArray = ["1", "2", "3", "4", "5"];
                    for (let i = 0; i < myArray.length; i++) {
                      $("#selectNumber").append("<option value='" + myArray[i] + "'>" + myArray[i] + "</option>");
                    }
                  </script>
                  

                  【讨论】:

                    【解决方案13】:

                    var list =["muez","devomech","solution"]
                    var option = "";
                              for(var i=0; i<list.length; i++){
                                option+= '<option value="'+ list[i] +'">' + list[i] + "</option>"
                              
                            }
                            document.getElementById("deviceoption").innerHTML = option;
                    &lt;select id="deviceoption"&gt;&lt;/select&gt;

                    `

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2012-01-03
                      • 1970-01-01
                      • 1970-01-01
                      • 2021-11-26
                      • 1970-01-01
                      • 2014-08-11
                      相关资源
                      最近更新 更多