我正在尝试创建一个动态页面,该页面根据下拉选择进行更改。所以对于设置,我有两个下拉菜单。描述它的最简单方法是国家和州下拉菜单。我想要它,以便在选择特定状态时,将单独的DIV填充有关该状态的信息。现在这只是一个例子,但它几乎是我正在寻找的。我已经使用一些简单的 Javascript 和数组设置了两个下拉列表来填充它们。
<script type="text/javascript">
var postState = '';
var postCountry = '';
var state = '\
US:AK:Alaska|\
US:AL:Alabama|\
US:AR:Arkansas|\
';
var country = '\
US:United States|\
';
function populateCountry(defaultCountry) {
if ( postCountry != '' ) {
defaultCountry = postCountry;
}
var countryLineArray = country.split('|'); // Split into lines
var selObj = document.getElementById('countrySelect');
selObj.options[0] = new Option('Select Country','');
selObj.selectedIndex = 0;
for (var loop = 0; loop < countryLineArray.length; loop++) {
lineArray = countryLineArray[loop].split(':');
countryCode = TrimString(lineArray[0]);
countryName = TrimString(lineArray[1]);
if ( countryCode != '' ) {
selObj.options[loop + 1] = new Option(countryName, countryCode);
}
if ( defaultCountry == countryCode ) {
selObj.selectedIndex = loop + 1;
}
}
}
function populateState() {
var selObj = document.getElementById('stateSelect');
var foundState = false;
// Empty options just in case new drop down is shorter
if ( selObj.type == 'select-one' ) {
for (var i = 0; i < selObj.options.length; i++) {
selObj.options[i] = null;
}
selObj.options[0] = new Option('Select State','');
selObj.selectedIndex = 0;
}
// Populate the drop down with states from the selected country
var stateLineArray = state.split("|"); // Split into lines
var optionCntr = 1;
for (var loop = 0; loop < stateLineArray.length; loop++) {
lineArray = stateLineArray[loop].split(":");
countryCode = TrimString(lineArray[0]);
stateCode = TrimString(lineArray[1]);
stateName = TrimString(lineArray[2]);
if (document.getElementById('countrySelect').value == countryCode && countryCode != '' ) {
// If it's a input element, change it to a select
if ( selObj.type == 'text' ) {
parentObj = document.getElementById('stateSelect').parentNode;
parentObj.removeChild(selObj);
var inputSel = document.createElement("SELECT");
inputSel.setAttribute("name","state");
inputSel.setAttribute("id","stateSelect");
parentObj.appendChild(inputSel) ;
selObj = document.getElementById('stateSelect');
selObj.options[0] = new Option('Select State','');
selObj.selectedIndex = 0;
}
if ( stateCode != '' ) {
selObj.options[optionCntr] = new Option(stateName, stateCode);
}
// See if it's selected from a previous post
if ( stateCode == postState && countryCode == postCountry ) {
selObj.selectedIndex = optionCntr;
}
foundState = true;
optionCntr++
}
}
function initCountry(country) {
populateCountry(country);
populateState();
}
</script>
我对 Javascript 不是很好,所以就我所知。如果有更简单的方法来填充下拉列表,我完全赞成。我在 PHP 方面非常有经验,所以我希望有某种交叉来显示内容。
重申一下,我有两个下拉菜单。选择 1 中的选项,2 中会出现不同的选项。单击 2 中的选项,信息会显示在下面的 DIV 中。用户应该能够继续选择选项和显示信息。