我有一个选择菜单、一个对象和一个函数,它将selectedValue
作为对象的数组返回给我。如何在函数之外访问choosenArray
?
我试图将choosenArray
声明为全局变量,但它不起作用。它只适用于"car1"
,因为它首先被选中。有什么建议吗?
HTML:
<select id="list" onchange="getSelectValue();">
<option value ="car1">car1</option>
<option value ="car2">car2</option>
<option value ="car3">car3</option>
<option value ="car4">car4</option>
Javascript:
<script>
var carData = {
"car1": [1, 5, 6, 7],
"car2": [4, 6, 8, 3],
"car3": [6, 7, 3, 4],
"car4": [3, 7, 2, 1]
};
var choosenArray;
function getSelectValue() {
selectedValue = document.getElementById("list").value;
console.log(selectedValue);
choosenArray = carData[selectedValue];
console.log(choosenArray);
return choosenArray;
}
var valueOfchoosenArray = getSelectValue(); //does not work for car2, car3, car4
console.log(valueOfchoosenArray); //does not work for car2, car3, car4
</script>
在中更改您的选择
<select id="list" onchange="useSelectValue()">
然后写一个函数:
var valueOfchoosenArray;
function useSelectValue() {
valueOfchoosenArray = getSelectValue();
console.log(valueOfchoosenArray);
//Do stuff
}
//You can use the value of valueOfchoosenArray here but code
write here is not is executed when you change the select value