javascript - 如何在不耗尽内存的情况下将所有城市加载到下拉列表中?

标签 javascript html drop-down-menu

我正在使用 http://www.javascriptsource.com/forms/country-state-city-drop-down-list.html 中包含的下拉列表

// State lists
var states = new Array();
states['Canada'] = new Array('Alberta', 'British Columbia', 'Ontario');
states['Mexico'] = new Array('Baja California', 'Chihuahua', 'Jalisco');
states['United States'] = new Array('California', 'Florida', 'New York');
// City lists
var cities = new Array();
cities['Canada'] = new Array();
cities['Canada']['Alberta'] = new Array('Edmonton', 'Calgary');
cities['Canada']['British Columbia'] = new Array('Victoria', 'Vancouver');
cities['Canada']['Ontario'] = new Array('Toronto', 'Hamilton');
cities['Mexico'] = new Array();
cities['Mexico']['Baja California'] = new Array('Tijauna', 'Mexicali');
cities['Mexico']['Chihuahua'] = new Array('Ciudad Juárez', 'Chihuahua');
cities['Mexico']['Jalisco'] = new Array('Guadalajara', 'Chapala');
cities['United States'] = new Array();
cities['United States']['California'] = new Array('Los Angeles', 'San Francisco');
cities['United States']['Florida'] = new Array('Miami', 'Orlando');
cities['United States']['New York'] = new Array('Buffalo', 'new York');

function setStates() {
    cntrySel = document.getElementById('country');
    stateList = states[cntrySel.value];
    changeSelect('state', stateList, stateList);
    setCities();
}

function setCities() {
    cntrySel = document.getElementById('country');
    stateSel = document.getElementById('state');
    cityList = cities[cntrySel.value][stateSel.value];
    changeSelect('city', cityList, cityList);
}

function changeSelect(fieldID, newOptions, newValues) {
    selectField = document.getElementById(fieldID);
    selectField.options.length = 0;
    for (i = 0; i < newOptions.length; i++) {
        selectField.options[selectField.length] = newOption(newOptions[i], newValues[i]);
    }
}

function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}
addLoadEvent(function() {
    setStates();
});
Head < script type = "text/javascript"
src = "countryStateCity.js" > << / script > Body < fieldset style = "width: 230px;" > <legend><strong>Make your selection</strong></legend> < p > <form name="test" method="POST" action="processingpage.php">
<table>
<tr>
<td style="text-align: left;">Country:</td>
<td style="text-align: left;">
<select name="country" id="country" onchange="setStates();">
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
<option value="United States">United States</option>
</select>
</td>
</tr><tr>
<td style="text-align: left;">State:</td>
<td style="text-align: left;">
<select name="state" id="state" onchange="setCities();">
<option value="">Please select a Country</option>
</select>
</td>
</tr><tr>
<td style="text-align: left;">City:</td>
<td style="text-align: left;">
<select name="city"  id="city">
<option value="">Please select a Country</option>
</select>
</td>
</tr>
</table>
</form> < /fieldset>

我的代码可以正常工作,但只能处理少量内容。当我将所有国家、州和地区以及城市和城镇加载到countryStateCity.js 文件中时,我的计算机内存不足。

“countryStateCity.js”文件很大。如果我列出所有国家、所有州和地区以及以“A”和“B”开头的国家的城市和城镇,一切正常,但如果我添加以“C”开头的国家的城市和城镇系统出现故障。

我需要将每个国家/地区的源文件分成 1 个,与此类似;

src="country/Canada.js"
src="country/Mexico.js"
src="country/United States.js"

我希望 Javascript 查找像country/Canada.js 这样的文件名,而不是在整个世界文件中查找名称。

有人可以为我提供修改后的“Javascript”编码吗?

最佳答案

好的。这很简单。我无权访问您的国家/地区文件,因此我不知道它的范围或分解方式、IE 数组或 JSON。所以我的代码只是你的代码的混搭,它不会工作。但它展示了如何通过快速的最终结果来解决您的问题,从而提高用户体验。

诀窍就是在需要时加载所需的数据。通常这是通过 API 完成的,您通过 ajax 调用它,告诉它您想要什么,然后它会将其发送回来,以便您的 UI 可以显示它。

在这种情况下,我们没有服务器,因此我们将通过将脚本动态加载到 dom 中来实现。在本例中,国家/地区数据填充了州和城市的数据。根据要求,每个国家/地区一份文件。

最好加载州数据,然后加载每个州的城市等等。如果内存有问题,还可能考虑是否应该从 Dom 中删除数据:

//
// Some globals to store what the user selects.
//
VAR _COUNTY, _STATE, _CITY;

//
// This will append scripts to the body so that you dont need to load all the 
// scripts in one go, this is the trick.
//
function addScript( src,callback) {
  var s = document.createElement( 'script' );
  s.setAttribute( 'src', src );
  s.onload=callback;
  document.body.appendChild( s );
}
//
// Get all the states based on country
// add the correct file to the dom
// ie: country/Canada.js
// these files would be better scoped geodata.country geodata.state.
//
// IMPORTANT CHANGE YOUR HTML SELECT HANDLER TO FIRE HERE.
// <select name="country" id="country" onchange="getStates();">
//
function getStates(){
	_COUNRTY = document.getElementById('country'),
	file = ["country/",_COUNTRY,".js"].join;
	addScript(file, setStates);	
};
//
// 
// Called when the script loads
//
function setStates() {
//
// Here is where we would do
// geodata.states for now I'm using your declaration of state.
//
var stateList = states;
changeSelect('state', stateList, stateList);
// Not sure why you are doing this they need to select a state first?
setCities();
}
//
// Called when they select a state, 
// I would replicate the state code and load all the cities per state.
// I would disable the city drop down until the states are loaded.
//
function setCities() {
_STATE = document.getElementById('state');
cityList = cities[_COUNTRY][_STATE];
changeSelect('city', cityList, cityList);
}

function changeSelect(fieldID, newOptions, newValues) {
selectField = document.getElementById(fieldID);
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++) {
selectField.options[selectField.length]=newOption(newOptions[i],newValues[i]);
}
}

function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}

addLoadEvent(function() {
setStates();
});

   

关于javascript - 如何在不耗尽内存的情况下将所有城市加载到下拉列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42327733/

相关文章:

html - 如何在 Wordpress 边栏中拆分小部件?

javascript - 如何在 angularjs 中使用服务或工厂

javascript - Google 时间轴重叠时间表

javascript - innerHtml 和 innerText 破坏 Internet Explorer 中的选项卡

javascript - 如何在 Chrome DevTools 中调试 ajax 请求中加载的 js

php - 打印下拉菜单的可见名称而不是其值名称

javascript - 表单在 php while 循环中呈现相同的数据

python - 使用 wtforms 和 sqlalchemy 在数据库中生成用户下拉列表

javascript - angularjs 选择下拉验证

javascript - 使用 jQuery 在另一个事件发生更改事件后弹出下拉菜单