将 onclick 值返回给 JavaScript 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10054097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
return onclick value to a JavaScript function
提问by Ganesh
I have created an anchor with an onclick event which calls a JavaScript function. The JavaScript function returns some value. I want to use that value in another JS function.
我创建了一个带有调用 JavaScript 函数的 onclick 事件的锚点。JavaScript 函数返回一些值。我想在另一个 JS 函数中使用该值。
e.g
loading()
will return some value which will get passed to another js function. How do I capture and store the return value, and then pass this value to that function?
eg
loading()
将返回一些将传递给另一个 js 函数的值。如何捕获和存储返回值,然后将此值传递给该函数?
回答by Chris Gessler
Can you simply call the outer function with the inner function?
你能简单地用内部函数调用外部函数吗?
function outerFunc(a)
{
alert(a);
}
function innerFunc()
{
return 'test';
}
onclick="outerFunc(innerFunc());"
Or, if you need to use the return value in another event, set a variable.
或者,如果您需要在另一个事件中使用返回值,请设置一个变量。
var retval;
function outerFunc()
{
if(retval) alert(retval);
}
function innerFunc()
{
retval = 'test';
return retval;
}
onclick="return innerFunc();"
In someother onclick event
在另一个 onclick 事件中
onclick="return outerFunc();"
回答by sakhunzai
a) Use a global variablee.g (also)
var passVar=null;
function A(){
//set value
passVar='hello';
}
function B(){
//get value
alert(passVar);
}
b) if your function is on ANOTHER page which is consuming the stored value, you might be using setItem() ,getItem() and more advance features of browsers to use browser session storagemechanism
b) 如果您的函数在消耗存储值的另一个页面上,您可能正在使用 setItem() 、getItem() 和浏览器的更多高级功能来使用 b 浏览器会话存储机制
回答by Phrogz
You mentioned in a comment you want to save it for later. You can use the fact that JavaScript functions are closures and thus have access to local variables declared in the same scope:
您在评论中提到要保存以备后用。您可以使用 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);
回答by Niet the Dark Absol
Something like this?
像这样的东西?
<a onClick="loading(myFunction());">
If myFunction()
is your original onClick code, it will get passed to loading
afterward.
如果myFunction()
是您的原始 onClick 代码,它将在loading
之后传递给。