jquery的return this.each()的作用

时间:2014-06-27 15:23:06   收藏:0   阅读:189
经常看到在运用jquery插件绑定事件时候,都会用到each。

下面来比较下使用return this和return this.each()在使用的区别。

注意:使用each的时候引用this,必须使用jquery包裹:$(this)。

 

 HTML代码

<data-x="one">Text one</p>
<data-x="two">Text two</p>
<data-x="three">Text three</p>
<data-x="four">Text four</p>

 

 

 JS代码:

$.fn.mangle = function(options) {
        this.append(‘ - ‘ + this.data(‘x‘));
        return this;
};

$.fn.mangle2 = function(options) {
        return this.each(function(){
          $(this).append(‘ - ‘ + $(this).data(‘x‘));
        });
};
//$(‘p‘).mangle(); 
$(‘p‘).mangle2(); 

 

 在控制台 结果看出:没有使用each的时候是对整体的元素批量操作,使用啦each时候可以分别对元素进行单独操作


 

jquery的return this.each()的作用,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!