chr*_*ris 6 javascript jquery jquery-plugins
好的,这是我第一次尝试创建一个jQuery插件,所以我目前正在修改教程.
我到目前为止
(function($)
{
$.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"});
})
}
return this;
};
})(jQuery);
Run Code Online (Sandbox Code Playgroud)
这适用于更改提供的元素的文本颜色.然而.我想为插件生效的元素添加功能.例如悬停或点击事件.但是我现在无法理解这个想法,因为它selector可以是任何东西.所以它不像我可以通过普通的jQuery方法那样硬编码某些东西.
那么,有了这个,我如何在渲染之后将这种类型的功能添加到事物中?
Dom*_*Dom 20
在创建插件时,很容易使事情过于复杂,所以尽量保持简单.
我已经为您提供了插件的两个示例tippedOff.这里也是两个插件的jsfiddle演示.
第一个使用原始代码(无意义更改):
$.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()
{
//bind mouseenter, mouseleave, click event
$(this).css({"color":"#F00"})
.mouseenter(function(){
$(this).css({"color":"green"});
})
.mouseleave(function(){
$(this).css({"color":"#F00"});
})
.click(function(){
$(this).html('clicked');
});
})
}
return this;
};
Run Code Online (Sandbox Code Playgroud)
但是,这个是基于您的原始代码.基本上,我使用这些提示重建了您的原始代码.这就是我亲自去做的事情.我还向您提供了以下细分所做的更改.(重大变化):
$.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');
});
});
}
Run Code Online (Sandbox Code Playgroud)
原始代码:
$.tippedOff = function(selector, settings) {
Run Code Online (Sandbox Code Playgroud)
更改:
$.fn.tippedOff = function( settings ) {
Run Code Online (Sandbox Code Playgroud)
评论:
$.tippedOff和之间的区别$.fn.tippedOff是巨大的!将插件添加到$.fn命名空间而不是$命名空间将阻止您必须提供selector并简化生活.
我个人喜欢这个答案,其中@Chad声明:
我遵循的经验法则是:使用$.当它不是DOM相关(如ajax),并使用$ .fn.当它对使用选择器抓取的元素(如DOM/XML元素)进行操作时.
原始代码:
if(settings){$.extend(config, settings);}
Run Code Online (Sandbox Code Playgroud)
更改:
var config = $.extend( {
'top':0,
'left':0,
'wait':3000
}, settings);
Run Code Online (Sandbox Code Playgroud)
评论:
有一种if说法是多余的..extend()做所有的工作为你.
原始代码:
var $elem = $(selector);
if($elem.length > 0)
{
$elem.each(function()
{
$(this).css({"color":"#F00"});
})
}
return this;
Run Code Online (Sandbox Code Playgroud)
更改:
return this.each(function() {
$this = $(this);
$this.css({ 'color': config.color});
});
Run Code Online (Sandbox Code Playgroud)
评论:
使用return this.each(function(){})是良好的做法并保持可链接性.不仅如此,你不再需要担心它selector的长度.
*注意:如果您想添加其他事件,请methods在插件中使用不同的内容:jQuery Doc Reference - Authoring Plugins.
我希望这有帮助,如果您有任何问题,请告诉我!
| 归档时间: |
|
| 查看次数: |
6475 次 |
| 最近记录: |