2011-12-13 177 views
0

我试图让我自己的图像旋转器,如果在屏幕上有多个图像旋转器,将工作。以下是我迄今为止得到:jquery将此传递给变量函数

// jQuery plugin to make image containers rotate. 
(function($){ 

    // Swap text with title attribute 
    $.fn.scWFWImageRotator = function() { 

     var rotatorTimeSwap = 6000; 

     $(this).find("img").removeClass("selected"); 
     $(this).find("img:first-child").addClass("selected"); 

     var rotatorImageChangeFunc = function(item) { 
      var rotatorImages = $(item).children("img"); 
      var imgSelected = $(item).children("img.selected"); 
      var rotatorImgCount = rotatorImages.length; 
      var rotatorCurImage = $(imgSelected).index(rotatorImages); 
      alert(item); 
     } 

     return this.each(function() { 

      var rotatorTimer; 
      var $this = $(this); 
      var func = $.proxy(rotatorImageChangeFunc, $this); 

      rotatorTimer = setInterval(func, rotatorTimeSwap); 

      $this.hover(
       function() { rotatorTimer = clearInterval(rotatorTimer); }, 
       function() { rotatorTimer = setInterval(func, rotatorTimeSwap); } 
      ); 

     }); 

    }; 

})(jQuery); 

问题是:rotatorImageChangeFunc = function(item) {项目不获取传递给函数。所以在这个函数里,我没有定义item。为什么会出现这种情况,我该如何解决?

回答

1

您传递给proxy的上下文参数被传递给函数this,而不是作为参数。只需将item更改为this即可。


备注:在您的主要功能中,您有几个$(this).find(...) s。插件功能看到的this已经一个jQuert对象(这就是为什么你的this.each(...)下面的作品),不需要再次调用$()。只需this.find(...)

1

$.proxy只设置this包装函数 - 它不会做任何与函数参数。

setInterval()将会调用您的代理函数而没有参数,因此原始 - item也将是未定义的。在函数的第一行

var item = this; 

要修复,从函数的声明删除item,做。

[或将所有对item的引用重新命名为this]。

-1

您还没有在其他地方定义变量项目。