Out*_*mer 7 javascript jquery plugins
我正在尝试编写一个插件,它将为jQuery包装器对象添加一些方法.基本上,我想像这样初始化它:
var smart = $('img:first').smartImage();
Run Code Online (Sandbox Code Playgroud)
'smartImage'插件会将2个方法附加到'smart'引用的对象,所以我将能够执行以下操作:
smart.saveState();
// do work
smart.loadState();
Run Code Online (Sandbox Code Playgroud)
不幸的是,我无法弄清楚如何将这两种方法附加到包装器对象.我的代码遵循典型的jQuery插件模式:
(function($)
{
$.fn.smartImage = function()
{
return this.each(function()
{
$(this).saveState = function() { /* save */ }
$(this).loadState = function() { /* load */ }
}
}
}
Run Code Online (Sandbox Code Playgroud)
在我调用smartImage()之后,既没有定义'saveState'也没有'loadState'.我究竟做错了什么?
您实际上是在smartImage()函数中返回一个jQuery对象.这是编写jQuery插件的正确方法,因此您可以将其与其他jQuery函数链接起来.
我不确定是否有办法做你想做的事.我会推荐以下内容:
(function($) {
var smartImageSave = function() { return this.each(function() { } ); };
var smartImageLoad = function() { return this.each(function() { } ); };
$.fn.extend( { "smartImageSave":smartImageSave,
"smartImageLoad":smartImageLoad });
});
var $smart = $("img:first");
$smart.smartImageSave();
$smart.smartImageLoad();
Run Code Online (Sandbox Code Playgroud)
这是我熟悉并成功使用的一种技术.
您不能以您演示的方式附加方法/属性,因为正如您所说,jQuery对象只是它包含的任何DOM元素的包装.你当然可以附加方法/属性,但是当jQuery再次选择它们时它们将不会持久存在.
var a = $('.my-object');
a.do_something = function(){ alert('hiya'); }
a.do_something(); // This alerts.
var b = $('.my-object');
b.do_something(); // Freak-out.
Run Code Online (Sandbox Code Playgroud)
如果您希望在第二次恢复时在jQuery对象上存在方法,则需要将其分配给jQuery.fn.因此,您可以定义辅助方法,将其分配给jQuery.fn,并使用jQuery数据设置为您维护状态...
$.fn.setup_something = function()
{
this.data('my-plugin-setup-check', true);
return this;
}
$.fn.do_something = function()
{
if (this.data('my-plugin-setup-check'))
{
alert('Tada!');
}
return this;
}
var a = $('.my-object').setup_something();
a.do_something(); // Alerts.
$('.my-object').do_something(); // Also alerts.
Run Code Online (Sandbox Code Playgroud)
我建议你看一下http://docs.jquery.com/Internals/jQuery.data和http://docs.jquery.com/Core/data#name
| 归档时间: |
|
| 查看次数: |
3111 次 |
| 最近记录: |