在javascript中工作时如何调用jQuery中定义的变量。基本上,我有这个:
(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是未定义的,但我不确定为什么。我是javascript的新手,所以任何信息都会有所帮助。
答案 0 :(得分:0)
您在您需要的函数无法访问的范围中定义了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*
}