【问题标题】:jQuery making plugin?jQuery制作插件?
【发布时间】:2013-04-29 13:08:12
【问题描述】:

如何在初始化函数中绑定滑动事件?我是插件开发新手,所以需要一点帮助?

我正在编码:

(function( $ ) { 

    var methods = { 

        init: function(){  

            return this.bind('click',methods.slide());

        },

        slide: function() {

            alert('I\'m sliding');

            // and lets the element color turns into green
            return this.css('color','green');            

        }

    };

    $.fn.myPlugin = function( method ) {

        if ( methods[method] ) {

            return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));

        } else if ( typeof method === 'object' || !method ) {

            return methods.init.apply( this, arguments );

        } else { 

            $.error( ' Method ' + method + ' doesn\'t exists in jQuery.myPlugin ');

        }

    }

})(jQuery)


$('#test').myPlugin();

<p id="test">Test</p>

我看到警报,但只有在开始时init,但如何在点击时绑定事件slide

【问题讨论】:

  • 我在@SpYk3HH 回答中添加了评论,仍然不介意如何在外面使用方法或参数。

标签: jquery jquery-plugins


【解决方案1】:

你的代码有什么问题:

至于你的代码有什么问题,return $(this).on('click', methods.slide()); .slide 后不需要()。您实际上是在告诉它立即进行调用,而不是分配函数。也改一下return $(this).on('click', methods.slide);

另外:return this.css('color','green'); 应该是 return $(this).css('color','green');


为了更好地解释 jQuery 插件:

以下是我最基本的jQuery插件布局模板。从中你可以设计几乎任何你想要的 jQuery 插件,并拥有大量的多功能性。这很不言自明。看看它,如果它有帮助,很好,如果没有让我知道,我会删除它作为答案。

/*  Example Plug-in Setup   */
(function($) {
    if (!$.myPlugin ) { // your plugin namespace
        $.extend({
            myPlugin : function(elm, command, args) {
                return elm.each(function(index){
                    /*  THIS IS WHERE YOUR HEAVY WORK IS DONE AT    */
                    // do work to each element as its passed through
                    // be sure to use something like
                    //      return elm.each(function(e) { dor work });
                    // as your final statement in order to maintain "chainability"
                });
            }
        });
        $.fn.extend({
            myPlugin : function(command) {
                //  nothing extra needed here. Simply plugin your namespace and account for any parameters you might need. remove the ones you dont.
                return $.myPlugin ($(this), command, Array.prototype.slice.call(arguments, 1));
                //  Params Explained: The first Param you "send" here is the jQuery Object of the "Element in Play".
                //      This is the element(s) to which work will be applied.
                //  The Second is like any other jQuery Plugin (like stuff seen in jQueryUI), often it is a "command", thus I named it command,
                //      Though, you might need it as an object, an array, or even undefined! You can make it whatever you want. Treat it
                //      like any other parameter in any other "function/method"
                //  The last Param being passed here is simply an array of ALL other arguments/parameters sent to the function, again, change as you need too
            }
        });
        $.myPlugin.props = {    //  This could be used to store "properties" for your plugin, such as "variable timers", etc...
            key1: "value",
            key2: "value"
        };
        $.myPlugin.methods = {  //  Here you might add more "functions/methods" needed to make you plugin work, such as loops, etc...
            key1: function(param) {

            },
            key2: function(param) {

            }
        };
        $.myPlugin.init = function(param) { //  Here I designate a special spot for a special function, Initialize.
                //  You don't have to use this, or any of these extra spots, this is just simply a good practice in my opinion
                //  This keeps a centralized area in your code for what is going on to "start" your plugin
            var key = "value",
                key2 = {
                    subKey: "value"
                };
                /*
                /  run any number of initializing functions here
                /  I prefer to make my param a value that can be a
                /   string with a possible object
                /    the string for holding a base configuration
                /    the object for any change in properties or base values for that config
                */
        };
        $.myPlugin.defaults = { //  Here is a section for possibly "overridable" options.
                //  Simple variables you "need" to make plugin work, but have a "default"
                //      value that can be overriden by a later coder
            key1: "value",
            key2: {
                prop1: {
                    subKey1: "value",
                    subKey2: "value"
                },
                prop2: {
                    subKey1: "value"
                }
            },
            key3: function(param) {

            }
        };
    }
})(jQuery);

只需使用$.extend({ 区域来构建您的插件,就好像它在 JavaScript 的普通区域一样。 fn.extend 将为 $.myPlugin("element selector", command, args) && $("element selector").myPlugin(command, args) 添加 jquery 样式标记。其余的只是不同事物的变量,您可能需要保留一个贯穿整个插件的命名空间,因此您不会踩到脚趾。


回答评论:在另一种方法中使用一种方法就像使用该方法一样简单。我认为您缺少的是插件的触发方式。您正在尝试使用一个旧示例,并且您的事件没有按您的预期触发。这是有多种原因的,但是您缺少的第一件事是 jQuery 的“关键”。你错过了你的可链接性。当你调用$.fn.extend 时,你是在告诉 jquery “嘿,我有一个元素对象,我希望你也添加属性,然后把我的对象还给我!”为了以“最简单”的格式做到这一点,让我们把你拥有的东西应用到我的插件的“一块”上,看看发生了什么。

首先,让我们确保您有一个命名空间用于“JUST YOUR PLUGIN”。这种方式没有其他插件可以与它争论,除非它首先被加载。这是制作“扩展”javascript插件的关键规则。

(function($) {
    if (!$.myPlugin ) { // your plugin namespace
        $.extend({
            myPlugin : function(elm, command, args) {

好的,我们的插件命名空间建立后,我们可以添加我们的“预期”工作。

            myPlugin : function(elm, command, args) {
                //  Here, I'm ensuring the return of the entire "element objecT" passed into this plugin,
                //      in our case `$('#test')`, tho it could be several elements such as `$("input, select, textarea")`
                return elm.each(function(index){
                    //  Here is where we apply work to EACH AND EVERY ELEMENT being sent in.
                    //      Keep in mind, prep work could be done before this,
                    //          for specific variables of data, however, only this
                    //          area affects the elements directly

                    //  The following will "asign" the method `.slide` from our OWN methods to the "click" function  of the element
                    $(this).on("click", function(e) $.myPlugin.methods.slide);
                });
            }
        });

现在我们将添加在我们的插件上进行“传统”jQuery 调用的功能。 $.myPlugin("#test")$("#test").myPlugin() 之类的东西

        //  this will simply add the ability to call our plugin via "traditional" jQuery Mark-up
        $.fn.extend({
            myPlugin : function(command) {
                return $.myPlugin ($(this), command, Array.prototype.slice.call(arguments, 1));
            }
        });

现在剩下的就是创建该幻灯片方法。 Initialize 已经通过上述工作建立,尽管您可以重构 return each 调用以在“init”作为参数发送时调用“only”,但这会导致很多“控制”问题。

        $.myPlugin.methods = {  //  Here you might add more "functions/methods" needed to make you plugin work, such as loops, etc...
            slide: function(param) {
                alert('I\'m sliding');
                // and lets the element color turns into green
                return $(this).css('color','green');            
            }
        };

最后,把它全部关闭!

    }
})(jQuery);

See jsFiddle Here for full working example!

【讨论】:

  • 对我来说太难了,抱歉
  • 认真的吗?那么你现在可能只想使用简单的 jQuery。这是我能想到的最基本的插件布局。这里唯一广泛的是名称空间的不断使用。这只是确保您的插件与其他插件配合得很好。
  • 我会为你添加更多的 cmets,也许它会有所帮助。但这确实是非常基本的。
  • @AviAtion Like This。这使用了您之前看到的一些内容,但希望能更好地解释它。希望您可以开始了解事情的发展方向。
  • @AviAtion 不要感觉太糟糕。老实说,我使用了完全相同的文档来尝试制作我的第一个插件,并且被所有 H311 混淆了!但后来我变得更好并开发了它。我可能应该把它写得很详细,但现在,这里有很多评论和例子。我希望你现在运气好一点。第一个插件总是最难的。
猜你喜欢
  • 2022-01-21
  • 2015-10-07
  • 1970-01-01
  • 2014-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
相关资源
最近更新 更多