我正在嘗試創建一個動態頁面,該頁面根據下拉選擇而變化。所以對於設置,我有兩個跌落。描述它的最簡單的方法將是一個國家和國家下降。我喜歡它,所以當選擇一個特定的狀態時,一個單獨的div會填充關於該狀態的信息。現在,這僅僅是一個例子,但它幾乎是我正在尋找的。我已經使用一些簡單的Javascript和數組來設置兩個下拉列表來填充它們。通過下拉填充Div
<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中。用戶應該能夠繼續選擇選項並顯示信息。