【发布时间】:2011-09-26 21:22:44
【问题描述】:
这是我第一次尝试创建 JQuery 插件,所以我为我的菜鸟道歉。我的问题是,当我尝试调用公共方法时,我相信插件正在重新初始化。这是一个简单的插件,它创建一个 div 并用瓷砖填充它,方法 .reveal() 应该删除瓷砖。
插件声明:
(function($){
$.fn.extend({
//pass the options variable to the function
boxAnimate: function(options) {
//Set the default values, use comma to separate the settings, example:
var defaults = {
bgColor: '#000000',
padding: 20,
height: $(this).height(),
width: $(this).width(),
tileRows:25,
tileHeight:$(this).height()/25,
tileCols:25,
tileWidth:$(this).width()/25,
speed: 500
}
var options = $.extend(defaults, options);
this.reveal = function(){
var lastTile = $('.backDropTile:last').attr('id');
var pos1 = lastTile.indexOf("_");
var pos2 = lastTile.lastIndexOf("_");
var lCol = parseInt(lastTile.substr(pos2+1));
var lRow = parseInt(lastTile.substr(pos1+1,(pos2-pos1)-1));
alert(lCol+' '+lRow+' #bdTile_'+lRow+'_'+lCol);
for(lRow;lRow>=0;lRow--){
//Iterate by col:
for(lCol;lCol>=0;lCol--){
$('#bdTile_'+lRow+'_'+lCol).animate({
opacity: 0
}, 100, function() {
$('#bdTile_'+lRow+'_'+lCol).remove();
});
}
}
alert(lCol+' '+lRow);
}
return this.each(function(index) {
var o = options;
//Create background:
$(this).prepend('<div id="backDrop" style="color:white;position:absolute;z-index:998;background-color:'+o.bgColor+';height:'+o.height+'px;width:'+o.width+'px;"></div>');
//create boxes:
//First iterate by row:
for(var iRow=0;iRow<o.tileRows;iRow++){
//Iterate by col:
for(var iCol=0;iCol<o.tileCols;iCol++){
$('#backDrop').append('<span class="backDropTile" id="bdTile_'+iRow+'_'+iCol+'" style="z-index:998;float:left;background-color:green;height:'+o.tileHeight+'px;width:'+o.tileWidth+'px;"></span>');
}
}
});
}
});
})(jQuery);
用法:
$(document).ready(function() {
$('#book').boxAnimate();
$('#clickme').click(function() {
$('#book').boxAnimate().reveal();
});
});
所以我几乎知道我的问题是什么,但我对创建 jQuery 插件来修复它还不够熟悉。似乎我读得越多,我就越感到困惑,因为实现这一目标的方法似乎有很多。
【问题讨论】:
-
您使用的是
data('boxAnimate'),您是否将插件实例存储在jQuery.data()的某个地方? -
对不起,这不是我使用的实际方法,我将其更改为我正在使用的方法。我在这里读过一个例子:msdn.microsoft.com/en-us/scriptjunkie/ff608209 我应该使用 .data
-
我认为将插件实例存储到 data() 中是正常的约定。 $('el').boxAnimate() 创建一个插件实例并将其附加到集合中的每个元素。 $('el').data('boxAnimate') 旨在检索附加的实例。
标签: jquery jquery-plugins methods