jQuery制作插件?

Sma*_*ash 1 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>
Run Code Online (Sandbox Code Playgroud)

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

SpY*_*3HH 6

您的代码中包含哪些内容:

至于你的代码中有什么破坏,return $(this).on('click', methods.slide()); 不需要()after .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);
Run Code Online (Sandbox Code Playgroud)

只需使用$.extend({区域来构建您的插件,就好像它是JavaScript的正常区域一样.在fn.extend将增加对jQuery的风格标记$.myPlugin("element selector", command, args)&& $("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) {
Run Code Online (Sandbox Code Playgroud)

好的,我们建立了插件命名空间,我们可以添加我们的"预期"工作.

            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);
                });
            }
        });
Run Code Online (Sandbox Code Playgroud)

现在我们将添加在我们的插件上进行"传统"jQuery调用的功能.像$.myPlugin("#test")OR 这样的事情$("#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));
            }
        });
Run Code Online (Sandbox Code Playgroud)

现在剩下的就是创建那个幻灯片方法.通过上面的工作已经建立了Initialize,尽管return each如果"init"作为参数被发送,你可以重新调用"仅"被调用的调用,尽管这会导致很多"控制"问题.

        $.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');            
            }
        };
Run Code Online (Sandbox Code Playgroud)

最后,关闭它!

    }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

有关完整的工作示例,请参见jsFiddle!