0


我有一个相当复杂的问题,我似乎无法解决。

当用户在文本框中输入某个“术语”时,我有一个填充选择列表的输入文本框字段。

例如:
- 如果用户在文本框中输入单词“Mercedes”,选择列表将填充“A-class”、“B-class”、“C-class”、“S-class”
- 如果他们在文本框中输入“Audi”,选择列表中填充了“A4”、“A5”、“A6”等。

到目前为止,这符合我的预期。但是,当用户从选择列表中选择一个模型时,我想创建一个<div>下面动态填充相应的选定车辆配件的内容。

这是我到目前为止的代码:

HTML

<div>
Manufacturer:<input type="text" id="car_manufacturer"/>
Model: <select id="car_model"></select>
</div>

<p>Vehicle Model Accessories:</p>
<div id="model_accessories">
<!--- Here is a list of the selected vehicle model's accessories. It will change when the model selection changes ------> 
</div>

Javascript

vehicleModels = {
   "Mercedes": ["A-class", "B-class", "C-class", "S-class", "SLK", "ML", ],
   "Audi": ["A3", "A4", "A5", "A6", "A7", "A8", ],
   "BMW": ["120", "320", "330", "520", "635", "745", ]
}

此函数获取文本框中的值并检查它是否在上面的对象中定义。如果是,则将相应的车辆型号附加到选择列表中。

    $('#car_manufacturer').change(function() {
            if(vehicleModels[$(this).val()]) { 
                $.each(vehicleModels[$(this).val()], function() { 
                    $('#car_model').append('<option>' + this + '</option>');
                 });
            } 
});​

问题就从这里开始了!我现在如何<div>用相应的选定模型的配件填充模型配件?以下是目前汽车配件的存放方式。

mercedes_accessories = ["Xenons", "Adaptive cruise control", "sunroof"];
bmw_accessories = ["Start/stop", "heated seats", "Leather trim"];
audi_accessories = ["Electric seats", "B&O Sound System", "Leather trim",];

任何帮助将不胜感激。如果问题有点模糊,我很抱歉,很难解释。谢谢!

4

2 回答 2

1

我会做这样的事情:

var vehicleModels = {
       mercedes: ["A-class", "B-class", "C-class", "S-class", "SLK", "ML", ],
       audi: ["A3", "A4", "A5", "A6", "A7", "A8", ],
       bmw: ["120", "320", "330", "520", "635", "745", ]
    },
    vehicleAcc = {
        a3 : ["Xenons", "Adaptive cruise control", "sunroof"],
        a4 : ["Xenons", "Adaptive cruise control", "sunroof"],
        a6 : ["Xenons", "Adaptive cruise control", "sunroof"]
    };


$('#car_manufacturer').on('change', function() {
    if(this.value.toLowerCase() in vehicleModels) { 
        $.each(vehicleModels[this.value.toLowerCase()], function(i,e) { 
            $('#car_model').append('<option>'+e+'</option>');
        });
    }
});

$('#car_model').on('change', function() {
    if (this.value.toLowerCase() in vehicleAcc) {
        $.each(vehicleAcc[this.value.toLowerCase()], function(i,e) {
            $('#car_model_acc').append('<option>'+e+'</option>');
        });
    }
});

小提琴

于 2012-10-29T23:28:58.840 回答
0

试试这个:

var accessories;

accessories.mercedes = ["Xenons", "Adaptive cruise control", "sunroof"];
accessories.bmw = ["Start/stop", "heated seats", "Leather trim"];
accessories.audi = ["Electric seats", "B&O Sound System", "Leather trim"];

$("#car_model").change( function( ) {

    // cache accessories for this manufacturer
    var arr = accessories[ $("#car_manufacturer").val().toLowerCase() ];

    for( var i = 0; i < arr.length; i += 1 ) {
       $("#accessories").append("<option>" + arr[i] + "</option>");
    }
});
于 2012-10-29T23:35:13.380 回答