我一直在關注這個guide on w3schools to dynamically change the elements of a dropdown select based off another dropdown select,如下所示:更改JavaScript數組值
要做到這一點的代碼如下:
<!DOCTYPE html>
<html>
<body>
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
<script>
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
</body>
</html>
不過,我注意到,對於第二個下拉列表中選擇,元素的值被編號,我想知道如何將這些值更改爲文本。
例如,在鏈接的示例中的第一選擇如下:
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
如果我設置的值先選擇沃爾沃,第二選擇如下:
<select id="carmodel">
<option value="1">V70</option>
<option value="2">XC60</option>
<option value="3">XC90</option>
</select>
我想相比於上述獲得:
<select id="carmodel">
<option value="V70">V70</option>
<option value="XC60">XC60</option>
<option value="XC90">XC90</option>
</select>
ChangeCarList函數在哪裏? – baao
請添加更多詳情 –
@baao它在演示鏈接。 – mistaq