javascript 在 JQUERY 中点击事件后获取返回结果
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8976347/
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
get returned result after click event in JQUERY
提问by John Doe
I have a function that return value and i executed the function after click event for example
我有一个返回值的函数,例如我在单击事件后执行了该函数
$("some_div").click( my_function());
The answer is how to get the returned value of the function.
答案是如何获取函数的返回值。
i couldn't use
我不能用
var something = $("some_div").click( my_function());
Thanks to every one who contribute the the question.I've got my answer.
感谢每一位提出问题的人。我已经得到了答案。
回答by Felix Kling
You have to pass a functionto click
, not its return value. In the event handler you can call your function and deal with the return value as you see fit:
您必须将函数传递给click
,而不是其返回值。在事件处理程序中,您可以调用您的函数并按照您认为合适的方式处理返回值:
$("some_div").click(function() {
var result = my_function();
// do whatever you want with `result`
});
The event handler is not called immediately, but some time later (when the element is clicked). Therefore it does not make sense for .click
to return a value.
事件处理程序不会立即调用,而是在一段时间后(单击元素时)调用。因此.click
返回一个值是没有意义的。
回答by Florian Rachor
You could declare a global Variable and write the result into that. Here is an example that writes the current event into global:
您可以声明一个全局变量并将结果写入其中。这是一个将当前事件写入全局的示例:
var global = ''
$("#some_div").click(function(e){
global = e;
});
回答by gdoron is supporting Monica
You can't get a return value, You only subsrcibe a callback
function that will be fire when clicking "some_div".
您无法获得返回值,您只能订阅一个callback
在单击“some_div”时会触发的函数。
If you want to use some value from callback
function, use it inside the function or save it in a hidden input
如果要使用callback
函数中的某个值,请在函数内部使用它或将其保存在hidden input
$("some_div").click(function() {
var someValue = foo();
$('#hiddenInputName').val(someValue);
});
//later on...
var extractedValue = $('#hiddenInputName').val();