选择列表不会更改所选项目DHTML

时间:2017-05-11 16:24:14

标签: javascript html select options dhtml

我开始开发网站(从0开始学习)。当然,我为我的健康无知而道歉(和我的英语水平)。 我有3个降序选择:第一个包含从数据库加载的选项列表(现在,我只从HTML加载)。根据所选的选项,第二个选择将加载其选项,依此类推,直到第三个选择。问题本身已解决,但是当您想要选择已在第二个选择中加载的选项时,请不要"单击"在他们。只允许您选择第一个选项。在这里,我留下代码,看看是否有人可以找到任何可能的解决方案(和很多错误^^ )。



var carsAndModels = {};
carsAndModels['Volvo'] = ['V70', 'XC60']; 
carsAndModels['Volkswagen'] = ['Golf', 'Polo']; 
carsAndModels['BMW'] = ['M6', 'X5'];
    
var speedsAndModels = {};
speedsAndModels['V70'] = ['150km/h', '180km/h']; 
speedsAndModels['XC60'] = ['160km/h', '190km/h'];
speedsAndModels['Golf'] = ['170km/h', '190km/h']; 
speedsAndModels['Polo'] = ['180km/h', '200km/h'];
speedsAndModels['M6'] = ['190km/h', '2000km/h']; 
speedsAndModels['X5'] = ['200km/h', '210km/h'];
    
function ChangeCarList() {
  var carList = document.getElementById('car');
  var modelList = document.getElementById('carmodel');
  var speedList = document.getElementById('speed');
  var selCar = carList.options[carList.selectedIndex].value;
  while (modelList.options.length) {
    modelList.remove(0);
    speedList.remove(0);
  }
  var cars = carsAndModels[selCar];
  if (cars) {
    for (i = 0; i < cars.length; i++) {
      var car = new Option(cars[i], i+1);
      modelList.options.add(car);
    }
  }
  ChangeModelList();
}
function ChangeModelList() {
  var modelListM = document.getElementById('carmodel');
  var speedListM = document.getElementById('speed');
  var indMod = modelListM.selectedIndex;
  var selMod = modelListM.options[indMod].text;
  while (speedListM.options.length) {
    speedListM.remove(0);
  }
  var speeds = speedsAndModels[selMod];
  if (speeds) {
    for (i = 0; i < speeds.length; i++) {
      var speed = new Option(speeds[i], i+1);
      speedListM.options.add(speed);
    }
  }
}
&#13;
<div class="">
  <div class="">
	  <span>Select the brand</span><hr>
		<select id="car" onchange="ChangeCarList()">
		  <option value="">-- Select --</option> 
			<option value="Volvo">Volvo</option> 
			<option value="Volkswagen">Volkswagen</option> 
			<option value="BMW">BMW</option> 
		</select>
	</div>
	<div class="">
		<span>Select the model</span><hr>
		<select id="carmodel" onchange="ChangeCarList()"></select>
	</div>
	<div class="">
		<span>Select the speed control</span><hr>
		<select id="speed"></select>
	</div>
</div>
&#13;
&#13;
&#13;

问题:如何通过外部文件中的标准W3School调用函数(&#34; ChangeCarList&#34;&amp;&#34; ChangeModelList&#34;)? 非常感谢你:)。

0 个答案:

没有答案