我已经创建了一个带有onclick事件的锚点,该事件调用JavaScript函数。JavaScript函数返回一些值。我想在另一个JS函数中使用该值。
例如,loading()将返回一些值,该值将被传递给另一个js函数。如何捕获并存储返回值,然后将该值传递给该函数?
发布于 2012-04-07 19:39:27
你能简单地调用外部函数和内部函数吗?
function outerFunc(a)
{
alert(a);
}
function innerFunc()
{
return 'test';
}
onclick="outerFunc(innerFunc());"或者,如果需要在另一个事件中使用返回值,请设置一个变量。
var retval;
function outerFunc()
{
if(retval) alert(retval);
}
function innerFunc()
{
retval = 'test';
return retval;
}
onclick="return innerFunc();"在某些其他onclick事件中
onclick="return outerFunc();"发布于 2012-04-07 21:19:57
a)使用global variable例如(also)
var passVar=null;
function A(){
//set value
passVar='hello';
}
function B(){
//get value
alert(passVar);
}b)如果您的函数位于正在使用存储值的另一个页面上,则可以使用setItem()、getItem()以及浏览器的更高级特性来使用browser session storage机制
发布于 2012-04-07 21:20:29
您在评论中提到,您希望将其保存以备以后使用。您可以利用JavaScript函数是闭包的这一事实,因此可以访问在同一范围内声明的局部变量:
var clickedValue; // No need to set a value here, just declare is
myAnchor.addEventListener('click',function(evt){
// Call the other function, setting the 'this' scope to be the anchor
// The scope of the variable set it the one above
clickedValue = someFunction.call(myAnchor,evt);
},false);
/* later on… */
otherFunction(clickedValue);https://stackoverflow.com/questions/10054097
复制相似问题