2013-10-02 32 views
-4

哪一個從下面的代碼1和代碼2是真的,而我們使用return this?如何在jquery插件中使用「return this」?

代碼1:

$.fn.greenify = function() { 
     $.each(function() { 
     this.css("color", "green"); 
     return this; 
     }; 
    }; 

碼2:

 $.fn.greenify = function() { 
     $.each(function() { 
     this.css("color", "green"); 
     }; 
     return this; 
    }; 
+2

你爲什麼不嘗試一下?或者至少,閱讀[複製此代碼的頁面]的其餘部分(http://learn.jquery.com/plugins/basic-plugin-creation/)? – George

+1

這些都不是工作示例。他們都有語法錯誤。 – meagar

+0

你的代碼中有哪部分你不明白? – SLaks

回答

1

這將是:

$.fn.greenify = function() { 
    return this.each(function() { 
     $(this).css("color", "green"); 
    }); 
}; 

返回傳遞的集合,以確保該插件可以鏈接。
在另一方面,如果這是你所有的插件不,沒有必要爲each

$.fn.greenify = function() { 
    return this.css("color", "green"); 
}; 
0

可以返回的.each()結果:

$.fn.greenify = function() { 
    return this.each(function() { 
    this.css("color", "green"); 
    }; 
}; 

見 「使用每個()方法」 一節plugin tutorial page

相關問題