javascript - 如何将变量值保留在函数之外?

标签 javascript jquery

我有以下两个函数,它们使用 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/

相关文章:

javascript - 重新加载自调用函数

javascript - 自动滚动 DIV -

javascript - ajax请求成功但看不到我的数据

javascript - 如何使用箭头键浏览 <li> 元素 - jQuery?

javascript - 使用 AJAX 将 Zip 文件上传到服务器

基于Javascript的数据表

javascript - 在页面中间创建iframe

javascript - VueJS : input with dynamic value + v-model

javascript - 将表列从一行移动到另一行

javascript - jQuery 动画淡入淡出……如何创建第二个事件?