我使用以下选择形式和功能首先选择传输类型,我希望根据我在第一阶段的选择获得第二种形式的汽车或摩托车列表。如果你能告诉我为什么我的功能不起作用以及我缺少什么,我将非常感激
<!doctype html>
<html>
<body>
<select id="transport" name="transport">
<option value="choose">Please choose a type</option>
<option value="cars">Cars</option>
<option value="motorcycles">Motorcycles</option>
</select>
<select id="model" name="model">
<option>Please choose a type first</option>
</select>
<input id="submit" type="submit" value="submit" />
</body>
<script>
(function(){
var type = document.getElementById('transport');
var model = document.getElementById('model');
var cars = {
Alfa_Romeo: '4 C Spider',
Aston_Martin: 'V12 Vantage',
Audi: 'A4 Allroad',
Ford: 'Focus'
};
var motorcycles = {
Yamaha: 'YZF-R6',
Kawasaki: 'Versys 650 LT',
Suzuki: 'Boulevard C50',
Honda: 'Super Cub C100'
};
addEvent(type, 'change', function() {
if (this.value === 'choose'){
model.innerHTML = '<option>Please choose a type first</option>';
return;
}
var models = getModels(this.value);
var options = '<option>Please choose a model</option>';
for (var key in models){
options += '<option value="' + key + '">' + models[key] + '</option>';
}
model.innerHTML = options;
});
function getModels(transport) {
if (transport === 'cars') {
return cars;
} else if (transport === 'motorcycles'){
return motorcycles;
}
}
}());
</script>
`
答案 0 :(得分:1)
使用addEventListener。检查此工作代码段
(function(){
var type = document.getElementById('transport');
var model = document.getElementById('model');
var cars = {
Alfa_Romeo: '4 C Spider',
Aston_Martin: 'V12 Vantage',
Audi: 'A4 Allroad',
Ford: 'Focus'
};
var motorcycles = {
Yamaha: 'YZF-R6',
Kawasaki: 'Versys 650 LT',
Suzuki: 'Boulevard C50',
Honda: 'Super Cub C100'
};
type.addEventListener('change', function() {
if (this.value === 'choose'){
model.innerHTML = '<option>Please choose a type first</option>';
return;
}
var models = getModels(this.value);
var options = '<option>Please choose a model</option>';
for (var key in models){
options += '<option value="' + key + '">' + models[key] + '</option>';
}
model.innerHTML = options;
});
function getModels(transport) {
if (transport === 'cars')
{
return cars;
}
else if (transport === 'motorcycles'){
return motorcycles;
}
}
}());
<select id="transport" name="transport">
<option value="choose">Please choose a type</option>
<option value="cars">Cars</option>
<option value="motorcycles">Motorcycles</option>
</select>
<select id="model" name="model">
<option>Please choose a type first</option>
</select>
<input id="submit" type="submit" value="submit" />