当创建插件时,很容易使事情变得过于复杂,因此请尽量保持简单明了。我为您提供了两个示例的tippedOff插件,这是两个插件的
jsfiddle demo。
第一个使用您原始代码(
未进行任何重大更改):
$.tippedOff = function(selector, settings)
{
var config = {
'top':0,
'left':0,
'wait':3000
};
if(settings){$.extend(config, settings);}
var $elem = $(selector);
if($elem.length > 0)
{
$elem.each(function()
{
$(this).css({"color":"#F00"})
.mouseenter(function(){
$(this).css({"color":"green"});
})
.mouseleave(function(){
$(this).css({"color":"#F00"});
})
.click(function(){
$(this).html('clicked');
});
})
}
return this;
};
这个方案基于你的原始代码,但我使用
这些技巧重新构建了它。这是我个人处理的方式。下面我还提供了一个变更明细。(
重大变更已完成):
$.fn.tippedOff = function(settings) {
var config = $.extend( {
'top':0,
'left':0,
'wait':3000,
'color': 'orange',
'hoverColor': 'blue'
}, settings);
return this.each(function() {
$this = $(this);
$this.css({ 'color': config.color})
.mouseenter(function(){
$this.css({ 'color': config.hoverColor });
})
.mouseleave(function(){
$this.css({ 'color': config.color });
})
.click(function(){
$this.html('clicked');
});
});
}
----------------------------------------
故障:
原始代码:
$.tippedOff = function(selector, settings) {
已更改:
$.fn.tippedOff = function( settings ) {
注释:
$.tippedOff
和$.fn.tippedOff
之间的区别非常大!将插件添加到$.fn
命名空间而不是$
命名空间将使您无需提供选择器
,从而使生活更加简单。
我个人喜欢这个答案,其中@Chad说:
我遵循的经验法则是:当它与DOM无关时(例如ajax),使用$。当它操作使用选择器获取的元素时(例如DOM / XML元素),请使用$.fn。
原始代码:
if(settings){$.extend(config, settings);}
已更改:
var config = $.extend( {
'top':0,
'left':0,
'wait':3000
}, settings);
注释:
使用if
语句是多余的。.extend()
会为您完成所有工作。
原始代码:
var $elem = $(selector);
if($elem.length > 0)
{
$elem.each(function()
{
$(this).css({"color":"#F00"});
})
}
return this;
已更改:
return this.each(function() {
$this = $(this);
$this.css({ 'color': config.color});
});
评论:
使用return this.each(function(){})
是一个好的实践方法,可以保持链式调用。不仅如此,你也不再需要担心selector
的长度问题。
*注意:如果您想添加其他事件,则在插件中使用不同的
方法
:
jQuery文档参考-编写插件。
我希望这可以帮助您,如果您有任何问题,请告诉我!
$elem.click(handler)
- Kevin B$
中,而不是通常的$.fn
原型,因此它确实需要一个选择器。(也可以指出这种模式是不好/错误的。) - Evan Davis