jsfiddle HTML:
<select class="s1"></select>
<select class="s2"></select>
JS:
var test = [
["a","bsafd","cfsaf"],
["b","cvxb","cfsf"],
["c","hjymb","cfsaf"],
["d","vhthb","fsfc","fasfsa"],
["e","fsdb","fsfac"],
["f","zxczb","vcxc","fsafsd"],
["g","yjhdb","bvcbc"],
["h","vbnvb","yutkfc"],
["i","nbcvnb","ndnfgnmc"],
["j","ikgnb","ncnc"],
["k","fgncb","kjuc"]
];
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option>"+test[i][0]+"</option>");
}
$(".s1").on("change", function(){
var value = $(this).val();
for(var i=0;i<test.length;i++){
if(test[i].indexOf(value)){
for(var j=0;j<test[i].length;i++){
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
});
});
我可以从数组测试中获取第一个值并附加到第一个选择区域。但我在第二步上堆积了。我想根据用户选择将值附加到第二个选择区域。
Fon实例,用户选择&#34; a&#34;。接下来的两个值应该附加到子数组的第二个区域,该区域以&#34; a&#34;为首。
有人能告诉我我做错了什么以及如何完成它?
答案 0 :(得分:0)
尝试以下代码[查看您错误的内联评论],
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option value='"+test[i][0]+"'>"+test[i][0]+"</option>");
// -----------------^ add value to all options
}
$(".s1").on("change", function(){
var value = $(this).val();
$(".s2").html('');// first make the second drop down blank
for(var i=0;i<test.length;i++){
if(test[i][0]==value){
for(var j=0,l=test[i].length;j<l;j++){
//----------------^ j++ not i++
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
});
});
或者,如果您将json设为key-value
对以区分不同下拉列表的数据,那么使用它会更简单,
// json where keys are used fro first drop down and its values are used for second one
var test = {
"a":["bsafd","cfsaf"],
"b":["cvxb","cfsf"],
"c":["hjymb","cfsaf"],
"d":["vhthb","fsfc","fasfsa"],
"e":["fsdb","fsfac"],
"f":["zxczb","vcxc","fsafsd"],
"g":["yjhdb","bvcbc"],
"h":["vbnvb","yutkfc"],
"i":["nbcvnb","ndnfgnmc"],
"j":["ikgnb","ncnc"],
"k":["fgncb","kjuc"]
};
$(function(){
$.each(test,function(i,v){
// store all keys to first drop down
$(".s1").append("<option value='"+i+"'>"+i+"</option>");
});
$(".s1").on("change", function(){
var value = this.value;
$('.s2').html('');
if(value){
// get the value for the key which is selected
$(test[value]).each(function(key,data){
$(".s2").append("<option value='"+data+"'>"+data+"</option>");
});
}
});
});
答案 1 :(得分:0)
$(".s1").on("change", function(){
var value = $(this).val();
var option = '';
for(var i=0;i<test.length;i++){
/* Checking for first index */
if(test[i][0] == value){
for(var j = 1;j<test[i].length;j++){
/* creating options */
option += '<option>'+test[i][j]+'</option>';
}
}
}
/* remove previous options and prepend new option by selection */
$(".s2").empty().prepend(option);
});
请试试这个..
答案 2 :(得分:0)
for(var i=0;i<test.length;i++){
if(test[i][0]==value){
(var j=1;j<test[i].length;j++){
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
答案 3 :(得分:0)