Javascript函数无法返回元素 [英] Javascript function fails to return element

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

问题描述

所以我现在正在为一个项目使用 Handsontable jQuery插件,我写了一些使用自定义函数。

So I'm working with the Handsontable jQuery plugin for a project at the moment, and I've written some custom functions to work with it.

我目前遇到问题的功能是我编写的用于返回当前所选单元格的功能(当用户只选择一个,而不是多个,并且是检查)。

The function I'm currently having trouble with is one I've written to return the currently selected cell(when the user has only selected one, not multiple, and yes that is checked for).

这是我的代码:

function getCurrentCell(){
    var selection = $('div.current');
    var left = selection.offset().left;
    var right = left + selection.width();
    var top = selection.offset().top;
    var bottom = top + selection.height();
    $('div.active').find('table').find('td').each(function(){
        if($(this).offset().left >= left && $(this).offset().left <= right && $(this).offset().top >= top && $(this).offset().top <= bottom){
            return this;
        }
    });
    return false;
}

然而,每当我调用函数时,例如:

However, whenever I call the function such as:

var cell = getCurrentCell();

然后尝试提醒(单元格) console.log(单元格),我得到 false 返回值。

And then attempt to alert(cell) or console.log(cell), I get a false return value.

我最初想的是坐标会以某种方式关闭,因此找不到符合条件的元素,所以我试图通过添加...来检查...

My initial thought would be that somehow the coordinates would be off, and therefore no element would be found matching the criteria, so I attempted to check by adding...

$(this).css('background-color', 'black');

...在返回此之前线。这样,如果找到了正确的表格单元格,它将在实际返回代码之前显示在屏幕上。有趣的是,正确的单元始终的背景颜色已正确更改。所以,这个函数找到正确的单元格,它正在if循环中执行代码,但是当我尝试将返回值捕获到变量中时,该变量总是为false。

...right before the return this line. That way, if the right table cell is found, it will show up on screen before actually returning in code. Funny thing is, the correct cell always has its background color changed properly. So, this function is finding the correct cell, and it is executing the code within the if loop, but when I try and capture the return value into a variable, that variable is always false.

任何帮助都会很棒!谢谢!

Any help would be great! Thanks SO!

推荐答案

您正在使用 .each()

You are using .each() with a function

.each(function(){
    ...
    return this;
});
return false;

这将从回调中返回(如果,可能会停止每个循环这个 false ),但永远不会突破并从外部 getCurrentCell 函数返回!所以,那个将永远返回 false

This will return from the callback (and maybe stop the each-loop if this was false), but never break out and return from the outer getCurrentCell function! So, that one will always return false.

快速修复:

var result = false;
<...>.each(function(){
    if (<condition>) {
        result = <found element>;
        return false; // break each-loop
    }
});
return result; // still false if nothing found

这篇关于Javascript函数无法返回元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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