我试图通过点击链接显示模态窗口。但是,控制台返回Uncaught TypeError: modal.open is not a function
。我检查确保我在所需的地方放置了冒号。任何有新鲜眼睛的人都知道我错过了什么?
<a href="" id="nav-download">DOWNLOAD</a>
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>"});
});
});
答案 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的答案。