在函数jquery之外使用变量

时间:2018-01-30 18:36:06

标签: javascript jquery

我如何在声明它的函数之外使用变量?

想要编辑完整的代码,在我的情况下获得更多帮助..



<CustomAction Id="LaunchApplication1" Property="WixShellExecTarget"Value="[#Setup.exe]" />
<CustomAction Id="LaunchApplication1"
    BinaryKey="WixCA"
    DllEntry="WixShellExec"
    Impersonate="yes" 
    Return="check"
    Execute="immediate"/>

<CustomAction Id="LaunchApplication2" Property="WixShellExecTarget" Value="[#a.png]" />  
<CustomAction Id="LaunchApplication2" 
    BinaryKey="WixCA" 
    DllEntry="WixShellExec"
    Impersonate="yes"
    Return="check"/>

<InstallExecuteSequence>
    <Custom Action="LaunchApplication1" After="InstallFiles"/>
    <Custom Action="LaunchApplication2" After="LaunchApplication1"/>
</InstallExecuteSequence>
&#13;
$(document).ready(function(){
    var bank_id = null;
    var purpose_id = null;
    $('#bank_id').on('change',function(e)
    {
        bank_id = e.target.value;
    });

    $('#purpose_id').on('change',function(e)
    {
        purpose_id = e.target.value;
    });

    var data = {
        "purpose_id" : purpose_id,
        "bank_id" : bank_id
    };

    $.post("financialLoans/getRates", data, function(result){
    });



});
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

您可以在所有函数之外使用var(与全局范围相同)来声明全局变量 注意:var将范围变量置于其所在的位置,函数外部是全局范围(或​​window对象,与第二个示例相同)

var myGlobalVariable;
$('#bank_id').on('change',function(e) { ... });

或者,您可以使用window属性:

$('#bank_id').on('change', function(e) {
    window.myGlobalVariable = ...
});

<小时/> 摘录示例:

&#13;
&#13;
//global variable
var globalVar = null;

$(document).ready(function(){
    //NOTE: bank_id is inside $(document).ready() scope, not global. But you still can use bank_id whenever you want inside this one.
    var bank_id = null;
    
    $('#bank_id').on('change',function(e) {
      //using bank_id inside $(document).ready() scope! :)
      bank_id = parseInt(e.target.value);
      globalVar = e.target.value;
    });
    
    $('#another_input').on('change', function(e) {
      //checking bank_id in another function! :D
      if(bank_id == 1){
        alert("Second input: " + e.target.value + " and bank_id is 1!");
      }else{
        alert("bank_id isn't 1. :(");
      }
      alert("Global variable changed too, it was null, and now have the same value as bank_id.\nCalling by name: " + globalVar + ".\nAnd calling by window object: " + window.globalVar + ".");
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" id="bank_id"/>
<input type="text" id="another_input"/>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

只需从某个函数中的事件处理程序传递变量:

$(document).ready(function(){
    var bank_id = null;
    $('#bank_id').on('change',function(e)
    {
        bank_id = e.target.value;
        changeSomething(bank_id);
    });

    function changeSomething(bank_id) {
       if(bank_id === "1"){
          console.log(bank_id);
       }
    }

});