在Jquery插件中,经常会有return this.each(function(){})出现,那么这是为什么呢?看以下例子:
现在我想扩展jquery,写一个通用的方法,用来改变html元素中html内容的值;
1。未使用return this.each(function(){});
<div class="test">
div1
</div>
<div class="test">
div2
</div>
<script type="text/javascript">
$.fn.addStr = function(str){
this.each(function(){
this.innerHTML = str;
} )
}
var obj = $(".test").addStr("add str");//obj is undefined
alert(obj instanceof jQuery);//false
</script>
此时,我们得到的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");现在我们可以继续调用jquery对象的方法.css("","");
alert(obj instanceof jQuery);//true
</script>
而现在,我们能够取得返回的jquery对象,可以进行链式调用。