[英]javascript, .split(), implement additional variable
我找到了城市,州下拉菜单的代码。 它可以完美地工作,但是我通过在以下代码中添加美国州来实现附加功能:
//countries array
var countries = Object();
countries['Africa'] = '|Algeria|Angola|Benin';
//state array
var city_states = Object();
city_states['United States'] = '|Washington DC||Alabama|Alaska';
这是美国城市的数组,但是我想添加一个州缩写,例如:DC,AL,AK等,以发送到如下菜单:
function setRegions()
{
for (region in countries)
document.write('<option value="' + region + '">' + region + '</option>');
}
function set_country(oRegionSel, oCountrySel, oCity_StateSel)
{
var countryArr;
oCountrySel.length = 0;
oCity_StateSel.length = 0;
var region = oRegionSel.options[oRegionSel.selectedIndex].text;
if (countries[region])
{
oCountrySel.disabled = false;
oCity_StateSel.disabled = true;
oCountrySel.options[0] = new Option('SELECT COUNTRY','');
countryArr = countries[region].split('|');
for (var i = 0; i < countryArr.length; i++)
oCountrySel.options[i + 1] = new Option(countryArr[i], countryArr[i]);
document.getElementById('txtregion').innerHTML = region;
document.getElementById('txtplacename').innerHTML = '';
}
else oCountrySel.disabled = true;
}
function set_city_state(oCountrySel, oCity_StateSel)
{
var city_stateArr;
oCity_StateSel.length = 0;
var country = oCountrySel.options[oCountrySel.selectedIndex].text;
if (city_states[country])
{
oCity_StateSel.disabled = false;
oCity_StateSel.options[0] = new Option('SELECT NEAREST DIVISION','');
city_stateArr = city_states[country].split('|');
for (var i = 0; i < city_stateArr.length; i++)
oCity_StateSel.options[i+1] = new Option(city_stateArr[i],city_stateArr[i]);
document.getElementById('txtplacename').innerHTML = country;
}
else oCity_StateSel.disabled = true;
}
function print_city_state(oCountrySel, oCity_StateSel)
{
var country = oCountrySel.options[oCountrySel.selectedIndex].text;
var city_state = oCity_StateSel.options[oCity_StateSel.selectedIndex].text;
if (city_state && city_states[country].indexOf(city_state) != -1)
document.getElementById('txtplacename').innerHTML = city_state + ', ' + country;
else document.getElementById('txtplacename').innerHTML = country;
}
我当时在考虑添加一个附加的State缩写数组,但我认为向已构建的数组中添加一个简单的State缩写将通过在setregions()中添加另一个值并使用+缩写+而不是+ region +来做就可以了。 有什么想法如何实施吗? -谢谢。
如果您具有状态(对象)数组而不是字符串数组,则可以执行以下操作:
function State(longName, shortName) {
this.longName = longName;
this.shortName = shortName;
}
我不知道缩写是什么,但是将它们像这样存储在数组中
var cityStates =“州:Abbrev |华盛顿特区:WDC | ETC:etc”
var stateNames = cityStates.split("|");
var states = new Array(stateNames.length);
for (i=0; i<states.length; i++)
var longName = stateNames[i].split(":")[0];
var shortName = stateNames[i].split(":")[1];
states[i] = new State(longName,shortName);
}
这将为您提供一个新的带有50个状态对象的“状态”数组,每个状态对象可以这样调用:
states[0] //(returns a State object at index 0)
states[0].longName //(returns the long name)
states[0].shortName //(returns the abbreviated name)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.