1

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

我正在编码:

(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在点击时绑定事件?

4

1 回答 1

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);

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


回答评论:在另一种方法中使用一种方法就像使用该方法一样简单。我认为您缺少的是插件的触发方式。您正在尝试使用一个旧示例,并且您的事件没有按您的预期触发。这是有多种原因的,但是您缺少的第一件事是 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”作为参数发送时被调用,但这会导致很多“控制”问题。

        $.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);

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

于 2013-04-29T13:11:39.920 回答