这样写有什么好的优化方法
var times3 = 0,times4 = 0;
$(".touch-right-3").on("click",function(){
times3 += 1;
left = -100 * times3 + "%";
if(times3<=4){
$(".list-content-3").animate({left:left});
}else if(times3>=4){
times3 = 4;
}
});
$(".touch-left-3").on("click",function(){
times3 -= 1;
left = -100 * times3 + "%";
if(times3>=0){
$(".list-content-3").animate({left:left});
}else if(times3<0){
times3 = 0;
}
});
$(".touch-right-4").on("click",function(){
times4 += 1;
left = -100 * times4 + "%";
if(times4<=4){
$(".list-content-4").animate({left:left});
}else if(times4>=4){
times4 = 4;
}
});
$(".touch-left-4").on("click",function(){
times4 -= 1;
left = -100 * times4 + "%";
if(times4>=0){
$(".list-content-4").animate({left:left});
}else if(times4<0){
times4 = 0;
}
});
//调用完pageNext函数之后,在pagePre方法中取到的page值仍然是初始设置的0,怎么取到pageNext方法中改变后的page的值?
问题出在
pageNext(".touch-right-3",page,".list-content-3");
pagePre(".touch-left-3",page,".list-content-3");
每次click点击,pageNext函数将page这个全局变量+1,pagePre将page这个全局变量-1,所以pagePre中alert的times在times的-1操作后始终为0;
另外不知道你return times有什么用。
解决办法:把pagePre中的-1放到DOM操作后面。
这个很明显,你是把page的值传入到函数体内部了,然后再对函数的time参数进行赋值,
times = 4; //你只是仅仅修改了times的值,但是重要的是你要修改page的值才有效:
//修改为:
page = 4; //这样赋值!才可以所有的函数内部复制都要把times换成page,函数可以去掉times参数
//因为你想让两个函数公用,那么就需要调用共同作用于的变量,
这是修改后的:可以直接看最后面的函数调用
var page = function(){
var that = this;
this.page = 0;
this.pagePre = function(selector,times,content){
this.page = times;
$(selector).on("click",function(){
that.page = that.page - 1;
alert(that.page);
var left = -100 * that.page + "%";
if(that.page>=0){
$(content).animate({left:left});
}else if(that.page<0){
that.page = 0;
}
})
};
this.pageNext = function(selector,times,content){
this.page = times;
$(selector).on("click",function(){
that.page = that.page+ 1;
var left = -100 * that.page + "%";
console.log(that.page);
if(that.page <= 4){
$(content).animate({left:left});
return that.page;
}else if(that.page >= 4){
that.page = 4;
return that.page;
}
})
};
return this;
}
//调用:
page().pagePre(selector,times,content);