2013-10-16 31 views
0

我已经写了这个基本的插件,但我想这样做,所以每个实例都有自己的变量。如何让每个jquery插件实例都有自己的变量?

如果我运行下面,计数器是共享的两个。

我怎样才能让每个人都有自己的变数?

HTML

<div class=one>one</div> 
<br> 
<div class=two>two</div> 

JS

$.fn.ishare = function(){ 

    $counter = 0; 
    $shell = $(this); 

    $shell.on('click',function(){ 
     console.log($counter++); 
    }); 

}; 


$('.one').ishare('green'); 

$('.two').ishare('yellow'); 

回答

0

您可以创建类似

$.fn.ishare = function(){ 
    return this.each(function(){ 
     var $counter = 0; 
     $(this).on('click',function(){ 
      console.log($counter++); 
     }); 
    }) 
}; 

演示:Fiddle

相关问题