在不使用jQuery的情况下使用JavaScript从多个不同的选定下拉列表项获取值
我希望能够从两个不同的下拉列表中选择多个值,并使用输出值调用单独的函数。我能够独立地获得每个值,但希望能够有一个函数同时获得这两个值在不使用jQuery的情况下使用JavaScript从多个不同的选定下拉列表项获取值,javascript,html,Javascript,Html,我希望能够从两个不同的下拉列表中选择多个值,并使用输出值调用单独的函数。我能够独立地获得每个值,但希望能够有一个函数同时获得这两个值 <!DOCTYPE html> <html> <body> <select id ="cars1"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <o
<!DOCTYPE html>
<html>
<body>
<select id ="cars1">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<select id ="cars2">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<script>
//select the value from the dropdown table with id ="cars1"
var selectCars1 = document.getElementById("cars1");
selectCars1.onchange = function start(){
var Cars1Value = selectCars1.options[selectCars1.selectedIndex].value;
alert(Cars1Value);
}
//select the value from the dropdown table with id ="cars2"
var selectCars2 = document.getElementById("cars2");
selectCars2.onchange = function(){
var Cars2Value = selectCars2.options[selectCars2.selectedIndex].value;
alert(Cars2Value);
}
</script>
</body>
</html>
沃尔沃汽车
萨博
欧宝
奥迪
沃尔沃汽车
萨博
欧宝
奥迪
//使用id=“cars1”从下拉表中选择值
var selectCars1=document.getElementById(“cars1”);
选择cars1.onchange=函数开始(){
var Cars1Value=selectCars1.options[selectCars1.selectedIndex].value;
警报(CARS1值);
}
//使用id=“cars2”从下拉表中选择值
var selectCars2=document.getElementById(“cars2”);
选择cars2.onchange=function(){
var Cars2Value=selectCars2.options[selectCars2.selectedIndex].value;
警报(CARS2值);
}
有几种方法可以做到这一点,但其中一种方法是将值存储在函数外部,以便在其他函数中使用
有关代码的其他修改,请参见内联注释:
沃尔沃汽车
萨博
欧宝
奥迪
沃尔沃汽车
萨博
欧宝
奥迪
//在每个函数之外设置变量,以便在函数之外使用它们
var selectCars1=document.getElementById(“cars1”);
var selectCars2=document.getElementById(“cars2”);
var cars1Value=“”;
var cars2Value=“”;
//不要使用.onXys属性。使用.addEventListener
选择cars1.addEventListener(“更改”,获取值);
选择cars2.addEventListener(“更改”,获取值);
函数getValues(){
cars1Value=selectCars1.value;//只需获取值,无需传递索引
cars2Value=selectCars2.value;//只需获取值,无需传递索引
doOtherWork();
}
函数doOtherWork(){
警报(cars1Value+“”+cars2Value);
}