jQuery插件多个实例,内部变量递增
我正在尝试制作一个jQuery插件,它将递增和递减一个变量(而不是一个元素的值!)。这是可行的,但多个实例正在递增同一个变量,并且不会为每个实例创建一个单独的值。jQuery插件多个实例,内部变量递增,jquery,plugins,multiple-instances,Jquery,Plugins,Multiple Instances,我正在尝试制作一个jQuery插件,它将递增和递减一个变量(而不是一个元素的值!)。这是可行的,但多个实例正在递增同一个变量,并且不会为每个实例创建一个单独的值。 这是我的代码: (function( $ ) { var current_value = 5; var maxs = 10; var container_id; $.fn.moveLeft = function(container_id){ return this.each(function() {
这是我的代码:
(function( $ )
{
var current_value = 5;
var maxs = 10;
var container_id;
$.fn.moveLeft = function(container_id){
return this.each(function()
{
if (current_value+1 <= maxs)
{
current_value++;
$("#"+container_id).animate({
marginLeft: "-=194px",
},200);
}
});
}
$.fn.moveRight = function(container_id){
return this.each(function()
{
if (current_value-1 >= 1)
{
current_value--;
$("#"+container_id).animate({
marginLeft: "+=194px",
},200);
}
});
}
})(jQuery);
(函数($)
{
无功电流_值=5;
var-maxs=10;
var容器id;
$.fn.moveLeft=函数(容器id){
返回此值。每个(函数()
{
如果(当前_值+1=1)
{
当前_值--;
$(“#”+容器id)。设置动画({
marginLeft:“+=194px”,
},200);
}
});
}
})(jQuery);
html部分:
<div id="back" onclick="$('#back').moveLeft('s1');" >BACK</div><div id="fward" onclick="$('#fward').moveRight('s1');" >FWARD</div>
<div id="s1">SOME CONTENT 1</div>
<div id="back2" onclick="$('#back2').moveLeft('s2');" >BACK</div><div id="fward2" onclick="$('#fward2').moveRight('s2');" >FWARD</div>
<div id="s2">SOME CONTENT 2</div>
反向
部分内容1
反向
部分内容2
我需要的是为每个实例获取单独的当前值。有人能指引我吗?我是jQuery新手…根据文档,您可以使用来存储状态
$.fn.moveLeft = function(container_id) {
return this.each(function() {
var $this = $(this), moveLeftValue = $this
.data('moveLeftValue')
|| 5;
if (moveLeftValue < maxs) {
$("#" + container_id).animate({
marginLeft : "-=194px"
}, 200);
$this.data('moveLeftValue', moveLeftValue + 1);
}
});
}
$.fn.moveLeft=函数(容器id){
返回此值。每个(函数(){
var$this=$(this),moveLeftValue=$this
.data('moveLeftValue')
|| 5;
if(moveLeftValue
根据文档,您可以使用存储状态
$.fn.moveLeft = function(container_id) {
return this.each(function() {
var $this = $(this), moveLeftValue = $this
.data('moveLeftValue')
|| 5;
if (moveLeftValue < maxs) {
$("#" + container_id).animate({
marginLeft : "-=194px"
}, 200);
$this.data('moveLeftValue', moveLeftValue + 1);
}
});
}
$.fn.moveLeft=函数(容器id){
返回此值。每个(函数(){
var$this=$(this),moveLeftValue=$this
.data('moveLeftValue')
|| 5;
if(moveLeftValue
您所说的每一个实例是什么意思请参见已编辑的问题。我必须分别移动“s1”和“s2”,直到达到“maxs”为止。你说的每一个实例是什么意思请看编辑后的问题。我必须分别移动“s1”和“s2”,直到达到“maxs”。