javascript 使用具有多个选项的数组填充下拉选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7601287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:39:40  来源:igfitidea点击:

Populate dropdown select with array-with multiple options

javascriptjquery

提问by Alex C

So I'm trying to populate a dropdown with the states, the value for the option should be the two characters value, and the text for the option should be the full state's name, using the code below is returning a value of 0,1,2,3... and returning all the options in the var as the text.

所以我试图用状态填充下拉列表,选项的值应该是两个字符的值,选项的文本应该是完整的状态名称,使用下面的代码返回值 0,1 ,2,3... 并将 var 中的所有选项作为文本返回。

var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR",...];
$.each(states, function(val, text) {
    $('#selector').append( $('<option> </option>').val(val).html(text) )
    });

回答by Blazemonger

Try this, using an object for statesinstead of an array. Same results, but it's more clear what's what and you're less likely to have problems if you accidentally skip a name or abbreviation:

试试这个,使用对象states代替数组。结果相同,但更清楚什么是什么,如果您不小心跳过名称或缩写,您不太可能遇到问题:

var states = {
    "Select State":"", 
    "Alabama":"AL", 
    "Alaska":"AK", 
    "Arizona":"AZ",  
    "Arkansas":"AR" 
};
var val, text;
for (text in states) {
    val = states[text];
    $('<option/>').val(val).text(text).appendTo($('#selector'));
};

http://jsfiddle.net/g59U4/

http://jsfiddle.net/g59U4/

回答by James Allardice

The problem is that the callback function provided to .eachresults in valcontaining the index of the current iteration (e.g. 0, 1, 2 etc.) and textcontaining the value of that index of the array.

问题是提供给.each结果的回调函数val包含当前迭代的索引(例如 0、1、2 等)并text包含该数组索引的值。

To achieve what you are trying to, you would probably be better off with a normal forloop:

为了实现您的目标,您可能最好使用正常for循环:

for(var i = 0; i < states.length; i+=2) {
    $("#selector").append($('<option> </option>').val(states[i+1]).html(states[i]));  
}

You would be even better off caching the jQuery object containing #selectoroutside of your loop, so it doesn't have to look it up every iteration.

缓存包含#selector在循环外部的 jQuery 对象会更好,因此不必每次迭代都查找它。

Here's a working exampleof the above.

这是上述的一个工作示例

Another option would be to use an object instead of an array, using the state name or abbreviation as the keys, and the other as the values. Edit: just like @mblase75 has done

另一种选择是使用对象而不是数组,使用状态名称或缩写作为键,另一个作为值。编辑:就像@mblase75 所做的一样

回答by Java Drinker

Well you have the jQuery.eachfunction arguments confused. The first is the index of the value in the array, and the second in the value itself. What you need to do is something like:

好吧,您对jQuery.each函数参数感到困惑。第一个是数组中值的索引,第二个是值本身。你需要做的是:

$.each(states, function(index) {
    if(index%2 > 0) {
        //continue, basically skip every other one. Although there is probably a better way to do this
        return true;
    }
    $('#selector').append( $('<option> </option>').val(states[index+1]).html(states[index]) )
});

回答by bfavaretto

That would be really straightforward if your array had two dimensions. Considering you really need to use the one-dimensional array you presented, you could do this:

如果您的数组有两个维度,那将非常简单。考虑到您确实需要使用您提供的一维数组,您可以这样做:

var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR"];
for(var i=1; i<states.length; i+=2) {
    $('#selector').append( $('<option value="' + states[i] + '">' + states[i-1] + '</option>').val(val).html(text) )
}

回答by ipr101

If you changed your array to be an array of objects, you could do something like this -

如果您将数组更改为对象数组,则可以执行以下操作 -

var states = [{"text":"Select State","val":""},{"text":"Alabama","val":"AL"}]; //etc
$.each(states, function(val, statedata) {
    $('#selector').append( $('<option> </option>').val(statedata.val).html(statedata.text) )
});

This change passes a JavaScript object in to the callback each time. The object has textand valproperties and is passed in to the callback as the statedataparameter. The valparameter holds the current index position of the array so it is not required to populate the select box.

此更改每次都会向回调传递一个 JavaScript 对象。该对象具有textval属性,并作为statedata参数传递给回调。该val参数保存数组的当前索引位置,因此不需要填充选择框。

Demo - http://jsfiddle.net/sR35r/

演示 - http://jsfiddle.net/sR35r/

回答by Eddie B

I have a similar situation populating a select list with a two-dimensional array as the result of an $.ajax callback ....

我有一个类似的情况,作为 $.ajax 回调的结果,用二维数组填充选择列表......

JSON ...     
[["AL","Alabama"],["AK","Alaska"],["AS","American Samoa"],["AZ","Arizona"] ... 

var stateOptions = $('#state');
var html ='';
for (var i =1; i<data.length; i++){
    html+= '<option value="' +data[i][0]+ '">' +data[i][1]+ '</option>';
}
stateOptions.append(html);


<form name="form" id="form">

<select name="state" id="state">
        <option value=''>State</option>
</select>

</form>