Jquery选择器长度返回0

时间:2015-10-06 09:53:41

标签: jquery

var app = app || {};

(function ($) {
    app.initialize = {
        init: function () {
            app.initialize.fullScreen();
        },
        fullScreen: function () {
            var scrHeight = $window.height();
            console.log($fullScreenEl.length);
            $fullScreenEl.css('height', scrHeight);
        }
    };

    app.documentOnReady = {
        init: function () {
            app.initialize.init();
        }
    };


    var $window = $(window),
        $fullScreenEl = $('.full-screen');

    $(document).ready(app.documentOnReady.init);

})(jQuery);

这是我的代码,当我运行代码$ fullScreenEl长度返回零时,我不明白为什么。如果从(function($){})(jQuery)移动Document就绪;然后$('。全屏')。lenght返回1.有人可以给我一些建议吗?

1 个答案:

答案 0 :(得分:2)

以这种方式改变:

(function ($) {
    app.initialize = {
        init: function () {
            app.initialize.fullScreen();
        },
        fullScreen: function () {

           var $window = $(window),
               $fullScreenEl = $('.full-screen');

            var scrHeight = $window.height();
            console.log($fullScreenEl.length);
            $fullScreenEl.css('height', scrHeight);
        }
    };

    app.documentOnReady = {
        init: function () {
            app.initialize.init();
        }
    };


    $(document).ready(app.documentOnReady.init);

})(jQuery);

您必须在文档准备好后选择元素。此外,通过移动$window函数内部的$fullScreenElfullScreen,性能更好,因为访问范围之外的变量比在同一范围内访问变量要慢。