我刚刚开始编写jQuery插件。我写了三个小插件,但是我只是简单地将代码行复制到我的所有插件中,而实际上并不知道它的含义。有人可以告诉我更多有关这些的信息吗?也许有一天写一个框架时会有用的解释:)
这是做什么的?(我知道它以某种方式扩展了jQuery,但对此还有其他有趣的信息)
(function($) {
})(jQuery);
以下两种编写插件的方式有什么区别:
类型1:
(function($) {
$.fn.jPluginName = {
},
$.fn.jPluginName.defaults = {
}
})(jQuery);
类型2:
(function($) {
$.jPluginName = {
}
})(jQuery);
类型3:
(function($){
//Attach this new method to jQuery
$.fn.extend({
var defaults = {
}
var options = $.extend(defaults, options);
//This is where you write your plugin's name
pluginname: function() {
//Iterate over the current set of matched elements
return this.each(function() {
//code to be inserted here
});
}
});
})(jQuery);
我可能离这里很远,也许所有的意思都一样。我很困惑。在某些情况下,这似乎不适用于我使用Type 1编写的插件。到目前为止,Type 3对我来说似乎是最优雅的,但我也想了解其他类型。
(function($) { })(jQuery)
您的消息说:“我知道它以某种方式扩展了jQuery [...]”。显然您不知道,因为您的陈述是100%错误的。顺便说一句,它可能会误导未来的读者。看一下这个:stackoverflow.com/a/32550649/1636522。
(function($) { })(jQuery);
包装代码,以便$
为jQuery
的是瓶盖内,即使$
手段得到它别的外,通常作为结果$.noConflict()
的例子。这样可以确保您的插件正常运行,无论是否$ === jQuery
:)