【问题标题】:Javascript return not workingJavascript返回不起作用
【发布时间】:2012-04-22 07:11:21
【问题描述】:

我有这个代码:

function get_id_from_coords (x, y)
{
    x = parseInt(x);
    y = parseInt(y);

    if (x < 0)
    {
        x = (x + 6) * 60;
    }
    else
    {
        x = (x + 5) * 60;
    }
    if (y < 0)
    {
        y = (y + 6) * 60;
    }
    else
    {
        y = (y + 5) * 60;
    }

    $('#planets').children().each(function(){
        if ($(this).attr('x') == x) {
            if ($(this).attr('y') == y) {
                alert (parseInt($(this).attr('id')));
                return parseInt($(this).attr('id'));
            }
        }
    });
}
alert(get_id_from_coords(x, y));

但是,从这段代码中,我得到了两个弹出窗口: 首先,从函数内部,我得到了正确的值(比如 63),但是当我提醒返回值时,我只是得到了 undefined。

【问题讨论】:

  • xy 是否在函数外部定义?
  • 是的,它们在函数内部正常工作
  • 我很确定return 没有损坏
  • Icyrock 的解决方案看起来不错 - 您的退货设置不正确。
  • @SnackerSWE,对于if (y &lt; 0){y = (y + 6) * 60;}else{y = (y + 5) * 60;},考虑将其缩小为y = (y+5+(y&lt;0))*60。 ;)

标签: javascript jquery return


【解决方案1】:

当你的函数没有返回时,你会得到未定义 - 最后一个语句是对 each 函数的调用,它不是 return 语句。如果你把一个回报,例如

...
return $('#planets').children().each(function(){
    if ($(this).attr('x') == x) {
        if ($(this).attr('y') == y) {
            alert (parseInt($(this).attr('id')));
            return parseInt($(this).attr('id'));
        }
    }
});

它会返回一些东西——在这种情况下,基于文档:

它将返回#planets 的子代。

如果你想找到一些专门使用each 的值,那么你可以这样做:

...
val toRet;
$('#planets').children().each(function(){
    if ($(this).attr('x') == x) {
        if ($(this).attr('y') == y) {
            toRet = parseInt($(this).attr('id'));
        }
    }
});
return toRet;

【讨论】:

  • @SnackerSWE - 也许你应该考虑接受答案?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-20
  • 2010-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
相关资源
最近更新 更多