JQuery Uncaught Type错误:modal.open不是函数

时间:2015-09-16 21:20:01

标签: jquery

我试图通过点击链接显示模态窗口。但是,控制台返回Uncaught TypeError: modal.open is not a function。我检查确保我在所需的地方放置了冒号。任何有新鲜眼睛的人都知道我错过了什么?

JSFIDDLE

HTML

<a href="" id="nav-download">DOWNLOAD</a>

JQUERY

var modal = (function(){
    var
    method = {},
    $overlay,
    $modal,
    $content;

    // Append the HTML
    $overlay = $('<div id="overlay"></div>');
    $modal = $('<div id="modal"></div>');
    $content = $('<div id="content"></div>');

    $modal.hide();
    $overlay.hide();
    $modal.append($content);

    $(document).ready(function(){
        $('body').append($overlay, $modal);
    });

    $('#overlay').click(function(e){
        e.preventDefault();
        method.close();
    });

    // Center the modal in the viewport
    method.center = function () {
        var top, left;

        top = Math.max($(window).height() - $modal.outerHeight(), 0) / 2;
        left = Math.max($(window).width() - $modal.outerWidth(), 0) / 2;

        $modal.css({
            top:top + $(window).scrollTop(),
            left:left + $(window).scrollLeft()
        });
    };

    // Open the modal
    method.open = function (settings) {
        $content.empty().append(settings.content);

        $modal.css({
            width: settings.width || 'auto',
            height: settings.height || 'auto'
        });

        method.center();

        $(window).bind('resize.modal', method.center);

        $modal.show();
        $overlay.show();
    };

    // Close the modal
    method.close = function () {
        $modal.hide();
        $overlay.hide();
        $content.empty();
        $(window).unbind('resize.modal');
    };

    return method;
});


$(document).ready(function() {
    $('#nav-download').click(function(e) {
        e.preventDefault();
        modal.open({content: "<p>Get a link to download our free mobile app to your smart phone!</p>"});
    });
});

2 个答案:

答案 0 :(得分:0)

var modal = (function(){
    // ...
});

modal是一个功能。它没有open属性。

我假设您打算运行该功能。尝试:

var modal = (function(){
    // ...
}());
// ^ Notice the `()` here

答案 1 :(得分:0)

modal是一个函数,而不是一个对象。你需要这样做:

var m = modal();
m.open(...);

或者在您分配modal时使用IIFE立即致电该功能,如Rocket Hazmat的答案。