2015-10-30 262 views
-1

所以,我有一个是通过选择jQuery对象返回undefined

$(window).scroll(function() { 
    console.log($("#content div").inview()); 
}); 

但是它返回undefined调用的函数。当我返回$ elems时,它向我显示了所有正确的元素,但是当我返回$ el时,它会给出未定义的元素。

$.fn.inview = function() { 

    var $elems = this; 

    function getViewportHeight() { 
     /*do tsoomething that works*/ 
     return height; 
    } 

    var vpH = getViewportHeight(), 
    scrolltop = (document.documentElement.scrollTop ? 
     document.documentElement.scrollTop : 
     document.body.scrollTop); 

    // return $elems.toArray(); 
    $elems.each(function() { 
     var $el = $(this) 
     height = $el.height() - (vpH/1.5), 
     inview = $el.data('inview') || false, 
     topofscreen = scrolltop, 
     botofscreen = topofscreen + vpH, 
     topofelement= $el.offset().top; 

     return $el; 


}; 
+0

[使用jQuery.each()时返回值的可能重复?](http://stackoverflow.com/questions/3820269/return-a-value-when-using-jquery-each) – JJJ

+1

'return $ elems.each(...);'from $ .fn.inview() –

回答

2

inview没有return语句,所以它总是返回undefined

当你return $el;你正在做它,你传递给$elems.each

匿名函数内部如果要返回的东西从inview那么你需要在该函数中的return语句。可能您希望在您拨打each之前创建一个阵列,每次绕着循环时将$el推入阵列,然后返回阵列。