【问题标题】:turn jQuery object/code into a plugin将 jQuery 对象/代码转换为插件
【发布时间】:2013-06-19 17:55:56
【问题描述】:

所以我已经阅读了一些教程,但我仍然对如何将我的特定标记系统变成一个可用的插件感到困惑。

我用一堆函数声明了以下对象:

var Tags = {};

Tags.Class = function() {
  ...
};

然后我声明原型:

Tags.TaggingForm = new Tags.Class();

// Only takes text input fields for now!
Tags.TaggingForm.prototype = {
    initialize: function(tag_field){
       ...
    },
    hideInputField: function() {
      ...
    },

然后我有使用该对象的实际函数调用:

Tags.make_tagging_input = function (id) {

var

 tagger = new Tags.TaggingForm(id);
...
 }

我只是想知道如何把它变成一个插件:我现在这样称呼它:

window.g_gloab_var = Tags.make_tagging_input("#id");

这个骨架不断被推荐,但我不知道如何应用它:

//You need an anonymous function to wrap around your function to avoid conflict

(函数($){

//Attach this new method to jQuery
$.fn.extend({ 

    //This is where you write your plugin's name
    tags_input: function() {

        //Iterate over the current set of matched elements
        return this.each(function() {

            //code to be inserted here

        });
        }
    });

//pass jQuery to the function, 
//So that we will able to use any valid Javascript variable name 
//to replace "$" SIGN. But, we'll stick to $ (I like dollar sign: ) )       
})(jQuery);

【问题讨论】:

  • 您是否尝试过使用this 来获取您想要处理的元素?您可以将您的原始代码放在插件文件中,并在最内部的函数中,在this上运行您的代码。

标签: javascript jquery plugins jquery-plugins


【解决方案1】:

现在没有时间深入研究这个,但我最喜欢的插件创建样板是Stefan Gabos's

良好的 cmets 并且很容易理解。希望有帮助。当我有更多时间时,我会稍后再回来查看,但希望这对现在有所帮助。

【讨论】:

    【解决方案2】:

    您可以使用您的原始代码并拥有这样的插件:

    (function($) {
    
    // your original code here
    $.fn.extend({ 
    
        tags_input: function(options) {
    
            //Iterate over the current set of matched elements
            // that we would call via $(selector).tags_input(options);
            // e.g. $('.tags_input').tags_input({a: true, b: "some string"});
            return this.each(function() {
    
                // call your plugin here,
                // options can be an object of parameters to the plugin
    
                // using your code and calling it on "this"
                // e.g. Tags.make_tagging_input("#" + this.id);
    
            });
            }
        });
    
    })(jQuery);
    

    【讨论】:

      猜你喜欢
      • 2017-09-23
      • 2016-04-09
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 2017-09-14
      • 2013-12-16
      相关资源
      最近更新 更多