0
我不明白爲什麼我在下面得到兩個不同的結果。我用的是最傳統的jQuery插件模式爲Provide Public Access to Default Plugin Settings,提供公共訪問默認插件設置:jquery插件不工作,除非將其移動到元素的末尾?
$.fn[pluginName].defaults = {
property: "value",
...
}
但我不能得到正確的結果。然後,如果我將default
作爲method
的一部分,我會得到正確的結果 - 爲什麼?
HTML,
<div class="hello1"></div>
jQuery的,
(function ($) {
var pluginName = 'hilight';
var methods = {
init: function(options){
var $this = this;
// Extend our default options with those provided.
// Note that the first argument to extend is an empty
// object – this is to keep from overriding our "defaults" object.
var o = $.extend(true, {}, $this[pluginName].defaults, options);
console.log(o.setup.element1);
// Call the local method from the plugin itself to get the processed options.
var o = $this[pluginName]('defaults',options);
console.log(o.setup.element1);
},
defaults: function(options) {
// Default options.
var defaults = {
setup: {
tester1: "hello1",
tester2: "hello2",
tester3: "hello3",
element1: $(".hello1"),
element2: $(".hello2"),
list: $('.list-item')
},
foreground: "red",
background: "yellow"
}
// Always leave this line here.
var options = $.extend(true, {}, defaults, options);
// Return the processed options.
return options;
}
}
$.fn[pluginName] = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || ! method) {
return methods.init.apply(this, arguments); // always change 'init' to something else if you different method name.
} else {
$.error('Method ' + method + ' does not exist on jQuery.plugin');
}
return this;
};
// Provide Public Access to Default Plugin Settings
// An improvement we can, and should, make to the code above is to expose the default plugin settings.
// This is important because it makes it very easy for plugin users to override/customize the plugin with minimal code.
// And this is where we begin to take advantage of the function object.
// @reference: http://learn.jquery.com/plugins/advanced-plugin-concepts/
// Plugin defaults – added as a property on our plugin function.
// This needs only be called once and does not
// have to be called from within a "ready" block
// $.fn.hilight.defaults.foreground = "blue";
$.fn[pluginName].defaults = {
setup: {
tester1: "hello1",
tester2: "hello2",
tester3: "hello3",
element1: $('.hello1'),
element2: $(".hello2"),
list: $('.list-item')
},
foreground: "red",
background: "yellow"
}
}(jQuery));
DOM已準備就緒,
$().hilight({setup:{tester1: "x"}});
結果,
Object[] // for --> var o = $.extend(true, {}, $this[pluginName].defaults, options);
Object[div.hello1] // --> var o = $this[pluginName]('defaults',options);
都應該是Object[div.hello1]
任何想法?
編輯:
,如果我在頁面結束後或元素移動插件,它的工作原理只是 - 怎麼來的?如果我想將插件放在頁眉中,我怎樣才能使它工作?
感謝您的回答。我確實用'$(document).ready(function()'和'window onload'封裝了它,但根本沒有運氣! – laukok