jQuery: выдается ошибка "A is undefined", а JSLint говорит "неправильно вызван jQuery (...)", что здесь не так? - PullRequest
1 голос
/ 27 марта 2011

Обычно я не публикую такого рода вещи, но у меня совершенно нет идей, и после нескольких часов попыток исправить это, я просто не знаю, где искать ошибку или что эта ошибка вообще означает.

Страница, которая разбивается, доступна здесь: http://staging.mathewhawley.com/

Я создал небольшой плагин columnizer jQuery, который, кажется, вызывает эту ошибку, но мне кажется, что все, что я написал вПлагин совершенно действителен.

При включении Firebug console и JSLint регистрируется следующее:

jQuery(...) called incorrectly
jquery.lint.js (line 96)
More info:
jquery.lint.js (line 111)
jQuery(...) called incorrectly
jquery.lint.js (line 96)
More info:
jquery.lint.js (line 111)
a is undefined
[Break On This Error] (function(a,b){function cg(a){return d...a:a+"px")}}),a.jQuery=a.$=d})(window);
jquery.min.js (line 16)

При нажатии на ссылку "дополнительная информация" я получаю следующее:

Location:
jquery.lint.js (line 111)

You passed: ["#projects", undefined, jQuery(Document index.php)]

Available signatures include:
jQuery(selector, [context])
jQuery(element)
jQuery(elementArray)
jQuery(jQuery object)
jQuery()
jQuery(html, [ownerDocument])
jQuery(html, props)
jQuery(callback)

Я использую последнюю версию jQuery через Google CDN (<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>).

Также для тех, кому не нравится смотреть на внешнюю страницу, вотмой сценарий колонизатора, который, кажется, ломает вещи:

script.js // this file invokes all javascript.
jQuery(document).ready(function($) {

    // helper
    function scrollable() {
        if ( $.browser.webkit ) { 
            return $('body'); 
        } else {
            return $('html');
        }
    }

    // =========================
    // = Stuff on the homepage =
    // =========================
    if ( $('#projects').length ) { 

        $('#projects').children().hide();

        // Create column layout
        $(window).load(function() {

            $('#projects').columnize();

            function _reveal( el ) {
                if ( el !== undefined ) { 
                    el.fadeIn( 100 , function() { _reveal($(this).next()); });
                }
            }
            _reveal( $('#projects').children().first() );
        });

    }

    // =============================
    // = Stuff on the project page =
    // =============================
    // Add sticky project info
    if ( $('#project').length ) { 

        $('article','#project').sticky();
        // Back to Top link
        $('nav a[href=#tothetop]').click(function(e) {
            e.preventDefault();
            scrollable().animate({'scrollTop':0}, 400);
        });

    }

});

.

 jquery.columnizer.js // the columnizer helper script
(function($){
    $.fn.extend({ 
        columnize: function(options) {

            var defaults = {
                columns : 3,
                gutter  : 20
            },
                options = $.extend(defaults, options),
                o = options,
                internal = {},
                _i = internal;

            _i.container        = $(this); // container
            _i.containerHeight  = 0; // container
            _i.items            = _i.container.children(); // elements inside container
            _i.w                = _i.items.first().width();
            _i.columns          = {};
            _i.colHeight        = {};

            // Setup the container and its children's position
            _i.container.css({
                'position': 'relative'
            }).children().css({
                'position': 'absolute'
            });

            // cycle through all items and place them into arrays by column
            _i.items.each(function(i) {

                var itemPlace = i%o.columns; // get the column
                var col = itemPlace + 1; // start index at 1

                if ( _i.columns[col] === undefined ) {
                    _i.columns[col] = [$(this)]; // if the column doesn't already exist create it
                } else {
                    _i.columns[col].push($(this)); // otherwise add the current element to the correct column
                }

                var left = itemPlace * (_i.w + o.gutter); // calculate the left offset for the columns

                $(this).css({
                    'left': left + 'px', // apply the offset
                    'margin-left': 0     // and make sure no margin-left is on the container
                });

            });

            // Cycle through the existing columns
            for (var x=1; x <= o.columns; x++) {

                if ( _i.colHeight[x] === undefined ) { // create variables for storing the top offset to be applied to elements of this column
                     _i.colHeight[x] = 0; // start at creating it and setting it to 0
                }

                $.each(_i.columns[x], function(z, el) { // within each column cycle through its items

                    $el = $(el);
                    $el.css('top', _i.colHeight[x]+'px'); // set the top offset
                    _i.colHeight[x] += $el.outerHeight(true); // then add this elements height to the same variable

                });

            };
            // go through the columns
            $.each(_i.colHeight, function(key, val) {
                if ( _i.containerHeight < val ) { 
                     _i.containerHeight = val; // if this column's height is greater than the currently stored height, replace the height with this one
                }
            });
            _i.container.css({
                'height': _i.containerHeight+'px', // set the outer container to the tallest column's height
                'overflow':'hidden'
            });
            // done.
        }
    });
})(jQuery);

Любая помощь будет очень цениться.*

Яннис

1 Ответ

2 голосов
/ 27 марта 2011

Ваш колонизатор по умолчанию имеет три столбца (columns равен 3 в его defaults объекте.) Когда вы вызываете его для "#projects", есть только две статьи. Ваш плагин (в строке 50, jquery.columnize.js) зацикливается от x = 1 до 3 на объекте только с двумя столбцами. Затем он передает нулевой объект в функцию each () jQuery, что и является причиной ошибки.

...