jQuery制作插件?

时间:2013-04-29 13:08:12

标签: jquery jquery-plugins

如何在init函数中单击滑动事件?我是插件开发的新手,所以我需要一点帮助吗?

我正在编码:

(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

1 个答案:

答案 0 :(得分:6)

代码中包含哪些内容:

至于代码中的内容,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)&amp;&amp;添加jquery样式标记。 $("element selector").myPlugin(command, args)。其余的只是变量,可能需要保留一个包含整个插件的命名空间的不同内容,因此您不会踩到脚趾。


回答评论:在另一种方法中使用一种方法就像使用该方法一样简单。我认为你缺少的是插件是如何被解雇的。你正试图利用一个旧的例子而你的事件没有像你期望的那样被解雇。这有多种原因,但是你缺少的第一件事就是jQuery的“关键”。你错过了你的可连环性。当你打电话给$.fn.extend时,你告诉jquery“嘿,我有一个元素obejct我也想让你添加属性,然后把我的对象还给我!”为了以“最简单”的格式执行此操作,让我们把你拥有的东西,并将其应用到我的插件的“片段”,看看发生了什么。

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

(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,尽管如果“init”作为参数被发送,你可以重构return each调用“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!