我想知道为什么在这么多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?
谢谢
最佳答案
$this 是人们用来将实际 jQuery 对象 $(this) 缓存在变量中的标准。
你可以随意命名它,有些人喜欢将其称为 $self。
例如
var $self = $(this)
当您查看代码时,它只会帮助您识别出它是一个 jQuery 对象而不是普通的 dom 对象。
当您只创建 jQuery 变量的一个实例时,它的性能会更好。
关于插件开发中的 jQuery $this 与 $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1158582/