试图制作一个简单的jquery插件,但无法弄清楚我在做什么错。它是设计成一个多步骤的表单,效果很好。 prevPage和nextPage方法的逻辑基本上是相同的,因此我将逻辑移到setPage()上,而不是从其他两个公共方法中调用它。所有3种方法都应该是公开的,并且可以从插件外部正常工作。以下示例运行良好,我可以将页面设置为该方法调用中的任何内容。但是我不能从prevPage或nextPage调用setPage,它说该功能不存在。我想这是一个范围问题,但无法弄清楚我做错了什么。
示例:
$thing = $('#demo').book();
$('#myButton').on('click', function(){
$thing.setPage(2);
});
插件
(function($){
$.fn.book = function(options){
var defaults = {
onPageChange: function(){},
speed: 500
};
var settings = $.extend(defaults, options);
if (this.length > 1){
this.each(function(){ $(this).book(options) });
return this;
}
var pageIndex = 0;
var $this = $(this);
var pages = $this.children('section').css({width:'100%',height:'100%',position:'relative'});
this.initialize = function(){
pages.hide();
pages.first('section').show();
pages.find('.page-next').on('click', this.nextPage);
pages.find('.page-prev').on('click', this.prevPage);
return this;
}
this.getPageIndex = function(){
return pageIndex;
}
this.getPageCount = function(){
return pages.length;
}
this.setPage = function(index){
if (index >= 0 && index < pages.length && index != pageIndex){
oldPageIndex = pageIndex; // retain for callback info
$currentPage = pages.eq(pageIndex);
$newPage = pages.eq(index);
pageIndex = index;
pageName = ($newPage[0].hasAttribute("name")) ? $newPage.attr('name') : null; // used in callback
if (typeof settings.onPageChange == 'function'){
settings.onPageChange.call(this, oldPageIndex, pageIndex, pages.length, pageName );
}
if (index > pageIndex){ // move forward
$currentPage.hide("slide", {direction:"left"}, settings.speed, function(){
$newPage.show("slide", {direction:"right"}, settings.speed);
});
}else{ // move back
$currentPage.hide("slide", {direction:"right"}, settings.speed, function(){
$newPage.show("slide", {direction:"left"}, settings.speed);
});
}
}
return this;
};
this.nextPage = function(){
return $this.setPage(pageIndex+1);
};
this.prevPage = function(){
return this.setPage(pageIndex-1);
};
return this.initialize();
};
}(jQuery));
答案 0 :(得分:0)
我将setPage的逻辑放入一个名为changePage()的私有方法中,然后从公共方法中调用它。这似乎工作正常。无论如何,这可能是更好的设计实践。