基本上,我将一个值作为参数传入函数,然后我想通过将该参数存储为变量来在另一个函数中使用相同的值。问题是如果我在第一个函数中定义变量,它只能在该函数中访问。我该怎么办?这是我的代码:
<html>
<body>
<script>
function showUser(selection) {
var selectedOption = selection;//THIS IS THE VARIABLE I WANT TO ACCESS IN ANOTHER FUNCTION
//Some code
}
function saveTime(solvedTime) {
//This is where I am using the variable
xmlhttp.open("GET","savetimes.php?q="+selectedOption+"&time="+solvedTime, true);
xmlhttp.send();
}
</script>
<form id="session">
<select name="sessions" onchange="showUser(this.value)">
<option value="1">Session 1</option>
<option value="2">Session 2</option>
</select>
</form>
<br>
<div id="timesList">
</div>
</body>
</html>
答案 0 :(得分:3)
在函数外声明您的变量。它将可访问该范围内的所有功能。要不使用全局范围对此对象进行变更,可以使用 IIFE 进行包装。使用addEventListener
来处理事件,这是处理事件的更好方法。如果在请求之前选择了任何值,请检查saveTime
。
(function() {
const sessions = document.getElementById('sessions');
let selectedOption;
sessions.addEventListener('change', function() {
selectedOption = this.value;
console.log(selectedOption);
});
function saveTime(solvedTime) {
if(selectedOption) {
xmlhttp.open("GET","savetimes.php?q="+selectedOption+"&time="+solvedTime, true);
xmlhttp.send();
}
}
})();
&#13;
<html>
<body>
<form id="session">
<select id="sessions" name="sessions">
<option value="1">Session 1</option>
<option value="2">Session 2</option>
</select>
</form>
<br>
<div id="timesList"></div>
</body>
</html>
&#13;