我是 Java 脚本新手。这里我有 2 个下拉菜单的工作示例Fiddle .
HTML:
<select id=a></select>
<select id=b></select>
<select id=c></select>
JavaScript:
var data = [ // The data
['ten', [
'eleven','twelve'
]],
['twenty', [
'twentyone', 'twentytwo'
]]
];
$a = $('#a'); // The dropdowns
$b = $('#b');
for(var i = 0; i < data.length; i++) {
var first = data[i][0];
$a.append($("<option>"). // Add options
attr("value",first).
data("sel", i).
text(first));
}
$a.change(function() {
var index = $(this).children('option:selected').data('sel');
var second = data[index][2]; // The second-choice data
$b.html(''); // Clear existing options in second dropdown
for(var j = 0; j < second.length; j++) {
$b.append($("<option>"). // Add options
attr("value",second[j]).
data("sel", j).
text(second[j]));
}
}).change(); // Trigger once to add options at load of first choice
让我知道如何在此代码中添加一个下拉菜单。
Thanks
尝试这样的事情..我不得不稍微改变一下结构data
目的。接下来要获取下拉菜单的值,您可以这样做.val()
var data = {
'ten': {
'eleven': [11, 1111, 111111],
'twelve': [12, 1212, 121212]
},
'twenty': {
'twentyone': [21, 2121, 212121],
'twentytwo': [22, 2222, 222222]
}
},
$a = $('#a'); // The dropdowns
$b = $('#b');
$c = $('#c');
for (var prop in data) {
var first = prop;
$a.append($("<option>"). // Add options
attr("value", first).
text(first));
}
$a.change(function () {
var firstkey = $(this).val();
$b.html(''); // Clear existing options in second dropdown
for (var prop in data[firstkey]) {
var second = prop;
$b.append($("<option>"). // Add options
attr("value", second).
text(second));
}
$b.change();
}).change(); // Trigger once to add options at load of first choice
$b.change(function () {
var firstKey = $a.val(),
secondKey = $(this).val();
$c.html(''); // Clear existing options in second dropdown
for(var i = 0; i < data[firstKey][secondKey].length; i++) {
var third = data[firstKey][secondKey][i]
$c.append($("<option>"). // Add options
attr("value", third).
text(third));
}
$c.change();
}).change();
检查小提琴
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)