2012-07-10 53 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對象。