gpt4 book ai didi

javascript - 在函数外部使用 jquery 变量

转载 作者:行者123 更新时间:2023-12-03 02:36:10 27 4
gpt4 key购买 nike

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

想要编辑完整代码,以获得更多帮助。

$(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){
});



});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" required="" id="bank_id" name="bank_id"><option selected="selected" value="">Select</option><option value="1">Foo.</option><option value="2">bar</option>
</select>
<select class="form-control" required="" id="purpose_id" name="purpose_id"><option selected="selected" value="">Select</option><option value="1">Foo.</option><option value="2">bar</option>
</select>

最佳答案

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

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

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

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

<小时/>片段示例:

//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 + ".");
});
});
<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"/>

关于javascript - 在函数外部使用 jquery 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48528308/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com