简体   繁体   中英

How to access a variable outside a function?

I have a select menue, an object and a function who gives me back the selectedValue as an array of the object. How can I access the choosenArray outside of the function?

I tried to declare the choosenArray as a global variable, but it does not work. It only works for "car1" , because its selected first. Any suggestions?

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>
 

Change your select in

<select id="list" onchange="useSelectValue()">

Then write a function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM