2012-04-16 21 views
0

我想在一個jQuery插件chainability工作,它工作正常使用jQuery clickbelow chainability,jQuery插件的每個並準備

$(document).ready(function(){ 


     $('.call-parent').parent_child({ 
      target: '.element' 
     }); 

     $('.call-child-1').click(function(){ 
      $(this).parent_child().child_1(); 
      return false; 
     }); 

     $('.call-child-2').click(function(){ 
      $(this).parent_child().child_2(); 
      return false; 
     }); 

    }); 

(function($) { 

     $.fn.extend({ 

      parent_child: function(options) { 

       var defaults = { 
        target:'' 
       } 

       var options = $.extend(defaults, options); 
       var o = options; 

       var $this = this; 

       var $cm = this.click(function(ei) { 


        alert('parent'); 
        $this.child_1(); 

        return false; 

       }); 


       $this.child_1 = function() { 

        alert('child 1'); 

       }; 


       $this.child_2 = function() { 

        alert('child 2'); 

       }; 

       return $cm; 

      } 
     }) 
    })(jQuery);​ 

,但我有錯誤,當我使用each或在插件ready,例如,

$(document).ready(function(){ 


     $('.call-parent').parent_child({ 
      target: '.element' 
     }); 

     $('.call-child-1').click(function(){ 
      $(this).parent_child().child_1(); 
      return false; 
     }); 

     $('.call-child-2').click(function(){ 
      $(this).parent_child().child_2(); 
      return false; 
     }); 

    }); 

(function($) { 

     $.fn.extend({ 

      parent_child: function(options) { 

       var defaults = { 
        target:'' 
       } 

       var options = $.extend(defaults, options); 
       var o = options; 

       var $this = this; 

       var $cm = this.each(function(ei) { 


        alert('parent'); 
        $this.child_1(); 

        return false; 

       }); 


       $this.child_1 = function() { 

        alert('child 1'); 

       }; 


       $this.child_2 = function() { 

        alert('child 2'); 

       }; 

       return $cm; 

      } 
     }) 
    })(jQuery);​ 

錯誤消息,

$ this.child_1不是一個函數[打破這個錯誤]

爲什麼我不能做到這一點與eachready?或者我做錯了嗎?

+1

函數表達式不會被掛起,所以當你設置'$ cm'時,'$ this.child_1'還不存在。 – Mathletics 2012-04-16 13:05:07

+0

明白了。謝謝回覆。 – laukok 2012-04-16 13:10:28

回答

0

我重申作爲一個答案我的意見,所以你可以接受:

var f = function() { ... }函數表達式不要讓懸掛方式命名的函數聲明function f() { ... }做。因此在each示例中,設置$cm在聲明之前調用$this.child_1。在第一個示例中,該函數在點擊時被調用,所以它在執行時已經被解析。

+0

感謝您的答案,Mathletics! :-) – laukok 2012-04-16 16:21:54

-1

請勿在插件上使用$。它與jQuery使用它衝突。也許使用別的,a

+0

'$'是插件中'jQuery'的本地副本;這裏沒有衝突。 – Mathletics 2012-04-16 13:06:09