我有以下两个函数,它们使用 onchange 从下拉菜单中获取输入
<script>
current_fin = "none";
current_mat = "Pine";
// Pass the current selection into a variable to use.
function getMaterial()
{
var mat = document.getElementById("dropdownone");
var current_mat = mat.options[mat.selectedIndex].text;
$("#price").html("Material is: " + current_mat + "<br/>" +"Finish is: " + current_fin);
}
function getFinish()
{
var fin = document.getElementById("dropdowntwo");
var current_fin = fin.options[fin.selectedIndex].text;
$("#price").html("Material is: " + current_mat + "<br/>" +"Finish is: " + current_fin);
}
</script>
它所做的就是将所选内容的值写入 div #price。现在当我改变一个然后另一个时,问题就出现了。如果我在两个框之间切换,变量将恢复为默认值 none 和 pine。我希望它们保留函数之外的值,因此,如果我将框 1 切换为 Oak,它会保持原样,直到我将其切换回来。我感觉这里有范围问题,但不知道如何继续。我将包含 HTML 以供引用。
<select name="material" id="dropdownone" onchange="getMaterial()">
<option>Pine</option>
<option>Oak</option>
<option>Walnut</option>
<option>Plastic</option>
</select>
<select name="finish" id="dropdowntwo" onchange="getFinish()">
<option>None</option>
<option>Finished</option>
</select>
<input type="submit" value="Submit To Cart">
<div id=price>
</div>
最佳答案
<script>
var current_fin = "none";
var current_mat = "Pine";
// Pass the current selection into a variable to use.
function getMaterial()
{
var mat = document.getElementById("dropdownone");
current_mat = mat.options[mat.selectedIndex].text;
$("#price").html("Material is: " + current_mat + "<br/>" +"Finish is: " + current_fin);
}
function getFinish()
{
var fin = document.getElementById("dropdowntwo");
current_fin = fin.options[fin.selectedIndex].text;
$("#price").html("Material is: " + current_mat + "<br/>" +"Finish is: " + current_fin);
}
当您在函数内写入 var current_mat
时,它会覆盖全局 current_mat
。
关于javascript - 如何将变量值保留在函数之外?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15893616/