【发布时间】:2011-08-08 22:43:25
【问题描述】:
调试我的一个项目时,我注意到另一位开发人员更改了 $(document).ready() 函数以在其自身内部生成一个闭包。例如。 $(document).ready(function($) { });我很好奇这样做的意义,以及它的用法。
注意:通过从函数中删除$,我的代码再次工作。 $(document).ready(function() { })
原始/固定代码
$(document).ready(function() {
var id = //pull session variable from asp session (yuck)
var img = $('.photoLink');
$('.photoLink').click(function() {
$(this).photoDialog({
id: id,
onClose: function() {
img.attr('src', img.attr('src') + '&rand=' + (new Date()).getTime()); //prevent caching of image
}
});
});
});
修改/损坏的代码
$(document).ready(function($) {
var id = //pull session variable from asp session (yuck)
var img = $('.photoLink');
$('.photoLink').click(function() {
$(this).photoDialog({
id: id,
onClose: function() {
img.attr('src', img.attr('src') + '&rand=' + (new Date()).getTime()); //prevent caching of image
}
});
});
});
修改后的代码会在 FireBug 中产生错误,指出我调用的自定义插件函数不存在。我假设这是因为 $ 参数覆盖或与尝试使用它的任何 jQuery 函数发生冲突。
我真的很困惑为什么有人会改变它,在当前的上下文中它没有任何意义,因为该插件调用是页面上唯一的 javascript。
有人可以向我解释一下您为什么要使用它,并可能举个例子来说明它的用法吗?
编辑
以下是我的自定义插件的代码,我还修改了上面的示例以显示我是如何调用它的:
(function($) {
var link = $('<link>');
link.attr({
type: 'text/css',
rel: 'stylesheet',
href: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/themes/black-tie/jquery-ui.css'
}).appendTo('head');
var script = $('<script>');
script.attr({
type: 'text/javascript',
src: 'https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.7/jquery-ui.min.js'
}).appendTo('head');
$.fn.photoDialog = function(options) {
var defaults = {
autoOpen: false,
title: 'Photo Tool',
minHeight: 560,
minWidth: 540,
url: '/photo_form.aspx',
onClose: function(){}
};
var opts = $.extend(defaults, options);
return this.each(function() {
$this = $(this);
that =$(this);
var $dialog = $('<div>')
.html('<iframe src="' + opts.url + '?sn=' + opts.id + '" width="' + (opts.minWidth - 20) + '" height="' + (opts.minHeight - 20) + '" style="border: none;" scrolling="no"></iframe>')
.dialog({
autoOpen: opts.autoOpen,
title: opts.title,
minHeight: opts.minHeight,
minWidth: opts.minWidth,
modal: true,
close: function() {
opts.onClose.call(that);
}
});
$this.click(function() {
$dialog.dialog('open');
return false;
});
});
};
})(jQuery);
【问题讨论】:
-
我刚刚在我的答案中添加了一个新理论...
标签: jquery closures document-ready