Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

jquery - Javascript function fails to return element

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).

Here is my code:

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();

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');

...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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are using .each() with a function

.each(function(){
    ...
    return this;
});
return 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.

Quick fix:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...