我一直在关注 standard创建 jQuery 插件的方法。特别是关于不污染 fn 命名空间的一点。但是,我遇到了一些奇怪的事情,它违反了它自己的“永远不要使用 $(this)
规则。
var methods = {
init : function( options ) {
return this.each(function(){
var $this = $(this), //HERE
data = $this.data('tooltip'),
tooltip = $('<div />', {
text : $this.attr('title')
});
// If the plugin hasn't been initialized yet
if ( ! data ) {
/*
Do more setup stuff here
*/
$(this).data('tooltip', {
target : $this,
tooltip : tooltip
});
}
});
},
在这种特殊情况下,重新评估 this
是否必要?如果是,为什么?
最佳答案
是的,是的。
在方法内部,this
指的是用于调用插件的 jQuery 对象,但您使用 each
循环遍历这些元素。在 each
的回调中,this
引用 jQuery 对象中的 DOM 元素,因此您需要为每个元素创建一个新的 jQUery 对象,以便在其上使用 jQuery 方法。
关于javascript - jQuery 的 "standard"插件模式是否需要 $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16411919/