在javascript中从jQuery调用变量
在使用javascript时,如何调用jQuery中定义的变量。基本上,我有:在javascript中从jQuery调用变量,javascript,jquery,Javascript,Jquery,在使用javascript时,如何调用jQuery中定义的变量。基本上,我有: (function ($) { function giveVariables() { var foo; var bah; $(document).bind('stuff' , function(e, superFoo, superBah) { foo = superFoo; bah = s
(function ($)
{
function giveVariables()
{
var foo;
var bah;
$(document).bind('stuff' , function(e, superFoo, superBah)
{
foo = superFoo;
bah = superBah;
});
return {fop: foo, bahp: bah}
}
})(jQuery);
function needVariables()
{
var neededVars = giveVariables();
fop = neededVars.fop;
bahp = neededVars.bahp;
*code that uses variables I passed*
}
显然,这并不是在拉变量。它告诉我,给定变量是未定义的,但我不知道为什么。我对javascript有点陌生,所以任何信息都会有帮助 您在所需函数无法访问的范围内定义了
foo
和bah
。就这么简单。如果希望在需要的地方可以访问,则需要在可以访问的范围内定义它们
//(function ($)
//{
function giveVariables()
{
var foo;
var bah;
$(document).bind('stuff' , function(e, superFoo, superBah)
{
foo = superFoo;
bah = superBah;
});
return {fop: foo, bahp: bah}
}
//})(jQuery);
function needVariables()
{
var neededVars = giveVariables();
fop = neededVars.fop;
bahp = neededVars.bahp;
*code that uses variables I passed*
}
如果您想保持原来的生活,需要将giveVariables
函数附加到窗口
(function ($)
{
function giveVariables()
{
var foo;
var bah;
$(document).bind('stuff' , function(e, superFoo, superBah)
{
foo = superFoo;
bah = superBah;
});
return {fop: foo, bahp: bah}
}
window.giveVariables = giveVariables;
})(jQuery);
function needVariables()
{
var neededVars = giveVariables();
fop = neededVars.fop;
bahp = neededVars.bahp;
*code that uses variables I passed*
}
您有没有理由必须将代码的前半部分放在自调用函数中?您还必须查看变量范围:要在自调用函数之外访问
foo
和bah
,您必须在它之外声明它们。标题毫无意义-jQuery是[a]JavaScript[library]。没有人会“在jQuery中定义变量”,相同的变量作用域概念会影响所有JavaScript代码。