【发布时间】:2009-07-21 11:15:50
【问题描述】:
我想知道为什么在这么多 jquery 插件中 $(this) 设置为指向 $this,这是一个示例,如果我在页面上包含以下两个插件:
(function($) {
jQuery.fn.pluginOne = function() {
return this.each(function() {
$this = $(this); <--
alert($this);
});
};
})(jQuery)
(function($) {
jQuery.fn.pluginTwo = function() {
return this.each(function() {
$this = $(this); <--
alert($this);
});
};
})(jQuery)
当我在 dom 上调用两个插件时:
$(document).ready({
$('.myClass').pluginOne();
$('.myOtherClass').pluginTwo();
});
第一个插件将从第二个插件获得 $this... 而我将 $(this) 指向一个本地变量:
(function($) {
jQuery.fn.pluginTwo = function() {
return this.each(function() {
var trigger = $(this); <--
alert(trigger);
});
};
})(jQuery)
一切正常,当然应该......
所以我的问题是......我应该什么时候使用 $this?
谢谢
【问题讨论】:
-
只是为了澄清......在上面的例子中 $('.myOtherClass').pluginTwo();将返回以下数组的第一个元素:$('.myClass')