jquery的return this.each()的作用

经常看到在运用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时候可以分别对元素进行单独操作


原文地址:https://www.cnblogs.com/heimanba/p/3810154.html