2012-07-10 54 views
1

我试图开发使用之间的“本”和jQuery的样板-V3.1和困惑“$(本)”jQuery插件样板元素

in the plugin 
    ... 
    $.fn[pluginName] = function (options) { 
    //alert($(this).toSource()); 
    return this.each(function() { 
     if (!$.data(this, 'plugin_' + pluginName)) { 
      $.data(this, 'plugin_' + pluginName, new Plugin(this, options)); 
     } 
    }); 
}; 

似乎new Plugin(this, options)不返回元素插件在Plugin.prototype上下文中。

取而代之,我将其修改为Plugin($(this), options)

eg. 
    $(function(){ 
    $('#container').myPlugin(); 
    }); 

不使用$(本)作为参数,我无法访问this.element在插件,.toSource()返回空对象({})

我正在通过修改$(this)来做正确的方式,或者如何通过this参数访问#container。

TIA。

+0

似乎这个世界有很多“样板”。我上面提到的是从[链接] http://jqueryboilerplate.com/下载的碟子。 – Gian 2012-07-10 04:44:24

回答

2

在插件,this指的是在应用插件jQuery对象,但回调this.each()内,this指的是jQuery对象内的每个单独的DOM元素。

所以,是的,你需要$(this)来获得一个包含循环内部的元素的jQuery对象。