這是我第一次嘗試創建一個JQuery插件,所以我爲我的noobbery道歉。我的問題是,當我嘗試調用公共方法時,我相信該插件正在重新初始化。這是一個簡單的插件,創建一個div,並用瓦片填充它,方法.reveal()應該刪除瓦片。jquery插件重新調用方法時調用
插件聲明:
(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()'某處? –
對不起,這不是我正在使用的實際方法,我將其更改爲我正在使用的方法。我在這裏讀過一個例子:http://msdn.microsoft.com/en-us/scriptjunkie/ff608209我應該使用它。數據 – jreed121
我認爲你將插件的一個實例存儲到data()中是正常的約定。 $('el')。boxAnimate()創建一個插件實例並將其附加到集合中的每個元素。 $('el')。data('boxAnimate')用於檢索附加實例。 –