使用数组填充下拉列表-具有多个选项 [英] Populate dropdown select with array-with multiple options

查看:65
本文介绍了使用数组填充下拉列表-具有多个选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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) )
    });

推荐答案

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

Try this, using an object for states instead 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:

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/

这篇关于使用数组填充下拉列表-具有多个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆