jQuery插件中为什么要return this.each?

来源:互联网 发布:js设置边框颜色 编辑:程序博客网 时间:2024/06/16 14:37

在Jquery插件中,经常会有return this.each(function(){})出现,那么这是为什么呢?看以下例子:

现在我想扩展jquery,写一个通用的方法,用来改变html元素中html内容的值;

1。未使用return this.each(function(){});

在Jquery插件中,经常会有return this.each(function(){})出现,那么这是为什么呢?看以下例子:现在我想扩展jquery,写一个通用的方法,用来改变html元素中html内容的值;1。未使用return this.each(function(){});

此时,我们得到的obj是undefined,也就是说如果我们想链式调用是不行的,如 :$(".test").addStr("add str").css("color","red")

2.使用return this.each(function(){});

<div class="test">      div1  </div>  <div class="test">      div2  </div>  <script type="text/javascript">          $.fn.addStr = function(str){              return this.each(function(){                  this.innerHTML = str;                  } )          }      var obj = $(".test").addStr("add str").css("color","red");<span style="color:#FF0000;">现在我们可以继续调用jquery对象的方法.css("","");</span>      alert(obj instanceof jQuery);//true   </script>  
 而现在,我们能够取得返回的jquery对象,可以进行链式调用。

转载:http://blog.csdn.net/wyb_gg/article/details/53580216