<!DOCTYPE HTML>
<html>
<head>
<meta charset="gb2312" />
<title></title>
<style>
</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<span>1</span>
<span>1</span>
<span>1</span>
<span>1</span>
<script>
$.fn.color = function(c){
this.each(function(){
$(this).css('color', c);
})
}
alert( $('span').color('red') ) //undefined

//加了 return this.each... 表示返回jQuery对象,以便链接式操作
$.fn.color2 = function(c){
return this.each(function(){
$(this).css('color', c);
})
}
alert( $('span').color2('blue').html(123) ) // object
</script>
</body>
</html>

解决方案 »

  1.   


    表示返回jQuery对象,以便链接式操作
    链接式操作是什么意思,能具体点吗?
      

  2.   

    return this.each(function(){}),each里面写个空的方法有什么意义?
      

  3.   


    那在each里面写空方法是为什么,下面的例子我看不太懂
    (function ($) {
      
        $.fn.objPinPuk = function (InIt) {
             this.onLoad = function () 
    {
                ......
             }
            this._resetPinUsingPuk = function() 
            {
               ........
            }
            return this.each(function (){
            });

    )(jQuery);
      

  4.   

    我来回答吧.首先在JQ中,each是遍历一个数组,比如你$('.some')返回的不一定只是一个jq对象,有可能是个数组,好多个elements.
    所以return this.each(){}是把所有你索引的对象都作用到这个插件下.
    你若保证你的插件每次都只会用一个JQ对象,那么你可以直接return this.
      

  5.   

    原文:
    When you filter elements with a selector ($('.myclass')), it can match more than only one element.
    With each, you iterate over all matched elements and your code is applied to all of them.
    链接:
    http://stackoverflow.com/questions/2678185/why-return-this-eachfunction-in-jquery-plugins