2011-06-24 81 views
0

我正在使用下面的代碼來循環,但一組元素。插件不工作,因爲我期望

$(this).next().show().animate({top: '25px'},250,function(){ 
       $(this).addClass('active'); 
      }); 

但這是有限的,因爲我需要去的元素的列表的末尾,並通過再次循環,所以我寫了這個插件:

(function($){ 
    $.fn.extend({ 
     rotater: function(class_check){ 
      return this.each(function(){ 
       if($(this).next().hasClass(class_check)){ 

        return $(this).next(); 
       } else { 

        return $(this).parent().children().first(); 
       } 
      }); 
     } 
    }); 
})(jQuery); 

爲了檢測,當我有達到了我所期望的集合(它們都共享一個共同的類)的結尾,如果是的話,抓住第一個重新開始整個循環的對象。

我改變調用代碼:

$(this).rotater('common_class').show().animate({top: '25px'},250,function(){ 
       $(this).addClass('active'); 
      }); 

,但它已不再完全是工作!我很困惑,我可以理解,如果我的「回到開始」腳本失敗,但至少第一個週期應該完全按照next()的行爲,因爲我的字面意思是返回next()的值。

我的HTML看起來像:

<div id="parent> 
    <div class="common_class"></div> 
    <div class="common_class"></div> 
    <div class="common_class"></div> 
    <div class="common_class"></div> 
    <div class="undesired_elemement"></div> 
</div> 
+0

您是否試過用Firebug或Chrome的開發人員工具逐步執行代碼?您將能夠看到以這種方式執行的代碼路徑,並檢查變量以查看任何給定時間的「this」。 – Spycho

回答

4

each回調回報沒有影響。你的旋轉函數返回任何返回的each,這不是回調函數返回的結果,但它會再次返回this

解決辦法:不要使用each

(function($){ 
    $.fn.extend.rotater = function(class_check){ 
     if(this.next().hasClass(class_check)){ 
      return this.next(); 
     else { 
      return this.parent().children().first(); 
     } 
    } 
})(jQuery); 

你只需要使用this.each如果你想一個功能應用到選擇器選擇的所有元素。

雖然選擇了多個元素,但您可能會遇到奇怪的行爲。在這種情況下,您應該明確選擇第一個元素:

var ele = this.eq(0); 
相關問題