如何从jQuery函数返回值? [英] How to return value from jQuery function?

查看:632
本文介绍了如何从jQuery函数返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从jQuery函数返回值。这是我的功能:

I am trying to return value from jQuery function. Here is my function:

 $('#output').keypress(function (event){ 
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        var read_lines = $('#output').val().split("\n");

        return  read_lines[read_lines.length-1];

    } 
    });

我希望将它返回的值保存在另一个变量中

and I want to save the value it return in another variable

var newRead = functionName(event);
alert (newRead);

我怎么能这样做,因为我无法访问功能。在此先感谢!

How can I do this because I am not able to access function. Thanks in advance!

推荐答案

在事件处理程序中,您应该调用其他函数而不是返回值。事件处理程序中的 function(){} 是一个回调函数。

In event handlers, you should call other functions instead of returning a value. function(){} in your event handler is a callback function.

在您的情况下,您可以直接在 keypress 事件中打印它们:

In your case, you can directly print them in the keypress event:

$('#output').keypress(function (event){ 
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        var read_lines = $('#output').val().split("\n");

        alert(read_lines[read_lines.length-1]);
    } 
});

或者你可以这样做:

$('#output').keypress(function (event){ 
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        var read_lines = $('#output').val().split("\n");

        MyFunction(read_lines[read_lines.length-1]);
    } 
});

function MyFunction(result){
      alert(result);
}

这篇关于如何从jQuery函数返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆