循环遍历<select>并以以下格式构建数组:"value1","value2","value3"

Chr*_*len 4 javascript jquery autocomplete

我想知道是否有人可以建议使用jQuery 循环遍历元素中的所有<option>s <select>并构建数组的最佳方法.

例如.

而不是以下内容,其中一个字符串ins传递给autoCompleteArray(),

$("#CityLocal").autocompleteArray(
        [
            "Aberdeen", "Ada", "Adamsville", "Zoar" //and a million other cities...
        ],
        {
            delay:10,
            minChars:1,
            matchSubset:1,
            onItemSelect:selectItem,
            onFindValue:findValue,
            autoFill:true,
            maxItemsToShow:10
        }
    );
Run Code Online (Sandbox Code Playgroud)

...我需要遍历所有的<options>a <select>并将它们推入一个数组,然后将该数组变量传递给函数而不是长字符串.

例如,

$("#CityLocal").autocompleteArray(
            [
                MyBigArrayOfOptions
            ],
            {
                delay:10,
                minChars:1,
                matchSubset:1,
                onItemSelect:selectItem,
                onFindValue:findValue,
                autoFill:true,
                maxItemsToShow:10
            }
        );
Run Code Online (Sandbox Code Playgroud)

如果您能建议如何以正确的格式将内容推送到数组中,我将不胜感激.我几乎怀疑这个站点上另一个帖子的循环部分.

谢谢.

Dam*_*kić 8

这应该工作:

$(document).ready(function(){
  // array of option elements' values
  var optionValues = [];
  // array of option elements' text
  var optionTexts = [];

  // iterate through all option elements
  $('#sel > option').each(function() {
    // get value/text and push it into respective array
    optionValues.push($(this).val());
    optionTexts.push($(this).text());
  });

  // test with alert
  alert(optionValues);
  alert(optionTexts);
});
Run Code Online (Sandbox Code Playgroud)

鉴于您的select元素具有ID sel.


Mat*_*aim 6

jQuery.map功能可能是你在找什么.下面的代码将创建一个包含选项的所有值或文本值的数组<select>.

var values = jQuery.map(jQuery("#select")[0].options, function(option)
             {
                return option.value;
             });

var texts = jQuery.map(jQuery("#select")[0].options, function(option)
            {
                return option.innerHTML;
            });
Run Code Online (Sandbox Code Playgroud)