如何使用JQuery填充级联下拉列表我有以下问题:我开始用HTML和JS创建一个表单,有两个Dropdown(Country和City)。现在我想用JQuery创建这两个动态,以便只有所选国家/地区的城市可见。我已经开始使用一些基本的JS工作正常,但在IE中遇到了麻烦。现在我正在尝试将我的JS转换为JQuery以获得更好的兼容性。我原来的JS看起来像这样:function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Germany") {
var optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"];
} else if (s1.value == "Hungary") {
var optionArray = ["|", "pecs|Pecs", "budapest|Budapest", "debrecen|Debrecen"];
} else if (s1.value == "Russia") {
var optionArray = ["|", "st. petersburg|St. Petersburg"];
} else if (s1.value == "South Africa") {
var optionArray = ["|", "midrand|Midrand"];
} else if (s1.value == "USA") {
var optionArray = ["|", "downers grove|Downers Grove"];
} else if (s1.value == "Mexico") {
var optionArray = ["|", "puebla|Puebla"];
} else if (s1.value == "China") {
var optionArray = ["|", "beijing|Beijing"];
} else if (s1.value == "Spain") {
var optionArray = ["|", "barcelona|Barcelona"];
}
for (var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}};在这里我的Jquery:http://jsfiddle.net/HvXSz/我知道这很简单,但我看不到树木。
3 回答
Smart猫小萌
TA贡献1911条经验 获得超7个赞
它应该如此简单
jQuery(function($) { var locations = { 'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'], 'Spain': ['Barcelona'], 'Hungary': ['Pecs'], 'USA': ['Downers Grove'], 'Mexico': ['Puebla'], 'South Africa': ['Midrand'], 'China': ['Beijing'], 'Russia': ['St. Petersburg'], } var $locations = $('#location'); $('#country').change(function () { var country = $(this).val(), lcns = locations[country] || []; var html = $.map(lcns, function(lcn){ return '<option value="' + lcn + '">' + lcn + '</option>' }).join(''); $locations.html(html) });});
演示:小提琴
qq_花开花谢_0
TA贡献1835条经验 获得超7个赞
我为Country,State,City和Zip创建了级联下拉列表
它可能对某人有帮助。这里只发布了部分代码,你可以在jsfiddle上看到完整的工作示例。
//Get html elementsvar countySel = document.getElementById("countySel");var stateSel = document.getElementById("stateSel"); var citySel = document.getElementById("citySel");var zipSel = document.getElementById("zipSel");//Load countriesfor (var country in countryStateInfo) { countySel.options[countySel.options.length] = new Option(country, country);}//County ChangedcountySel.onchange = function () { stateSel.length = 1; // remove all options bar first citySel.length = 1; // remove all options bar first zipSel.length = 1; // remove all options bar first if (this.selectedIndex < 1) return; // done for (var state in countryStateInfo[this.value]) { stateSel.options[stateSel.options.length] = new Option(state, state); }}
添加回答
举报
0/150
提交
取消