87,919
社区成员
发帖
与我相关
我的任务
分享
//如你所示,插件构造一般如下:
$.fn.pluginName=function(){
...
return this.each(function(){
$(this)...
})
}
//调用插件的格式一般如下:
$('.className').pluginName();
如上所示,pluginName方法添加到jquery的原型上,所以凡是jquery对象都具有pluginName这么个方法,调用的时候自然是以对象属性的方式调用,所以你代码中的第一个this就是$('.className')这个jquery对象(但是这个jquery对象是个集合),第二个$(this)则指的是使用each对$('.className')进行遍历时的每个类名为className的元素所对应的的jquery对象。
(2)查查资料,把“原型”和“this关键字”关键字这两个点搞清楚,你就明白了。
<!doctype html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.3.min.js"></script>
<title>test</title>
</head>
<body>
<body>
<div class="div1">test</div>
<div class="div2">test</div>
<div class="div3">test</div>
<script type="text/javascript">
$.fn.test = function(){
console.log(0, this);
console.log(1, $(this));
console.log(2, (this == $(this)));
return this.each(function(){
var obj = $(this);
console.log(3, $(this));
console.log(4, this);
});
}
$('.div1').test();
$('.div2').test();
$('.div3').test();
</script>
</body>
</html>
根据以上测试代码,说一下我的理解,不一定准确,但可以参考。
表面上看,this == $(this) 是false,但是从0,1的结果来看,他们指向的是同一个对象。
这样,来说,this.each与$(this).each();的区别不大,然后这里边的this的指向的是每次调用方法的那个元素。正因为一个插件在一个页面内可能多次调用,所以才有了return this.each();这种写法。
就是这块:
$('.div1').test();
$('.div2').test();
$('.div3').test();
而each里边的$(this)指向的是每次进入循环的jquery元素,如果是this的话,则是dom元素。
其实驾驭jquery的根本还是js的基础,所以有空看看js基础。