【问题标题】:Populate dropdown select with array using jQuery使用 jQuery 使用数组填充下拉选择
【发布时间】:2010-08-10 04:38:16
【问题描述】:

我正在尝试使用 jQuery 使用数组填充下拉选择。

这是我的代码:

        // Add the list of numbers to the drop down here
        var numbers[] = { 1, 2, 3, 4, 5};
        $.each(numbers, function(val, text) {
            $('#items').append(
                $('<option></option>').val(val).html(text)
            );            
        // END

但我遇到了一个错误。每个功能都是我从这个网站上得到的。

是否因为我使用的是一维数组而爆炸?我希望选项和文本都相同。

【问题讨论】:

  • 在 DOM 上一次添加一个项目被认为是非常缓慢的,并且强烈不建议。更具表现力的方式是构建一个字符串并在循环之后附加它

标签: jquery


【解决方案1】:

尝试循环:

var numbers = [1, 2, 3, 4, 5];

for (var i=0;i<numbers.length;i++){
   $('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items');
}

更好的方法:

var numbers = [1, 2, 3, 4, 5];
var option = '';
for (var i=0;i<numbers.length;i++){
   option += '<option value="'+ numbers[i] + '">' + numbers[i] + '</option>';
}
$('#items').append(option);

【讨论】:

  • 如果您处理的数组不是数字或不是来自安全来源,您应该使用列出的第一种技术,除了使用.text(number[i]) 而不是.html(number[i])。这将确保您不会冒任何注入漏洞的风险。
【解决方案2】:

数组声明的语法不正确。请尝试以下方法:

var numbers = [ 1, 2, 3, 4, 5]

循环部分似乎正确

$.each(numbers, function(val, text) {
            $('#items').append( $('<option></option>').val(val).html(text) )
            }); // there was also a ) missing here

正如@Reigel 所做的那样,似乎增加了一点性能(在如此小的阵列上并不明显)

【讨论】:

  • 如果您有预定义的键,这是最好的选择
【解决方案3】:

你也可以这样做:

var list = $('#items')[0]; // HTMLSelectElement
$.each(numbers, function(index, text) { 
    list.options[list.options.length] = new Option(index, text);
}); 

【讨论】:

    【解决方案4】:

    一种解决方案是创建您自己的 jquery 插件,该插件采用 json 映射并使用它填充选择。

    (function($) {     
         $.fn.fillValues = function(options) {
             var settings = $.extend({
                 datas : null, 
                 complete : null,
             }, options);
    
             this.each( function(){
                var datas = settings.datas;
                if(datas !=null) {
                    $(this).empty();
                    for(var key in datas){
                        $(this).append('<option value="'+key+'"+>'+datas[key]+'</option>');
                    }
                }
                if($.isFunction(settings.complete)){
                    settings.complete.call(this);
                }
            });
    
        }
    
    }(jQuery));
    

    你可以这样调用它:

    $("#select").fillValues({datas:your_map,});
    

    优点是在任何地方你都会遇到同样的问题

     $("....").fillValues({datas:your_map,});
    

    瞧!

    你可以在你的插件中添加你喜欢的功能

    【讨论】:

      【解决方案5】:
      var qty = 5;
      var option = '';
      for (var i=1;i <= qty;i++){
         option += '<option value="'+ i + '">' + i + '</option>';
      }
      $('#items').append(option);
      

      【讨论】:

        【解决方案6】:
        function validateForm(){
            var success = true;
            resetErrorMessages();
            var myArray = [];
            $(".linkedServiceDonationPurpose").each(function(){
                myArray.push($(this).val())
            });
        
            $(".linkedServiceDonationPurpose").each(function(){
            for ( var i = 0; i < myArray.length; i = i + 1 ) {
                for ( var j = i+1; j < myArray.length; j = j + 1 )
                    if(myArray[i] == myArray[j] &&  $(this).val() == myArray[j]){
                        $(this).next( "div" ).html('Duplicate item selected');
                        success=false;
                   }
                } 
            });
            if (success) {
                return true;
            } else {
                return false;
            }
            function resetErrorMessages() {
                $(".error").each(function(){
                    $(this).html('');
                });``
            }
        }
        

        【讨论】:

        • 我在您的代码中的任何地方都没有看到任何提及或暗示 &lt;option&gt; 标记的内容。你能解释一下这个答案吗?
        【解决方案7】:

        我使用的解决方案是创建一个使用 jquery 的 javascript 函数:

        这将在 HTML 页面上填充一个下拉对象。请让我知道这可以在哪里进行优化 - 但可以正常工作。

        function util_PopulateDropDownListAndSelect(sourceListObject, sourceListTextFieldName, targetDropDownName, valueToSelect)
        {
            var options = '';
        
            // Create the list of HTML Options
            for (i = 0; i < sourceListObject.List.length; i++)
            {
                options += "<option value='" + sourceListObject.List[i][sourceListTextFieldName] + "'>" + sourceListObject.List[i][sourceListTextFieldName] + "</option>\r\n";
            }
        
            // Assign the options to the HTML Select container
            $('select#' + targetDropDownName)[0].innerHTML = options;
        
            // Set the option to be Selected
            $('#' + targetDropDownName).val(valueToSelect);
        
            // Refresh the HTML Select so it displays the Selected option
            $('#' + targetDropDownName).selectmenu('refresh')
        }
        
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        

        【讨论】:

          【解决方案8】:

          由于我无法添加此as a comment,因此我会将其留在这里,以供任何发现反引号更易于阅读的人使用。它基本上是@Reigel 答案,但带有反引号

          var numbers = [1, 2, 3, 4, 5];
          var option = ``;
          for (var i=0;i<numbers.length;i++){
             option += `<option value=${numbers[i]}>${numbers[i]}</option>`;
          }
          $('#items').append(option);
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-11-27
            • 1970-01-01
            • 1970-01-01
            • 2015-08-24
            • 1970-01-01
            相关资源
            最近更新 更多