調試我的一個項目我注意到另一個開發者已經改變了$(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);
我剛剛給我的答案添加了一個新理論...... – Pointy 2011-04-19 19:24:32