jQuery插件创建和面向公众的方法 [英] jQuery plugin creation and public facing methods

查看:83
本文介绍了jQuery插件创建和面向公众的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个插件,可以使用DIV将HTML选择框转换为自定义下拉列表.

I have created a plugin to convert an HTML select box into a custom drop down using DIV's.

一切正常,但是我想使其更好一点. 请参阅我的jsFiddle

All works well, but i'd like to make it a little better. see my jsFiddle

在插件末尾,我有2种方法,slideDownOptions& slideUpOptions,我想在插件外部提供这些功能,以便其他事件可以触发操作.

At the end of the plugin I have 2 methods, slideDownOptions & slideUpOptions, I would like to make these available outside of the plugin so other events can trigger the action.

我对如何执行此操作有些困惑,更具体地说,是如何从插件内部以及从插件外部调用方法.

Im getting a little confused how to do this and more specifically how to call the methods from both within the plugin AND from outside of the plugin.

总是乐于助人的任何帮助

Any help always appreciated

推荐答案

考虑使用面向对象的代码重构插件.有了这个,您可以为插件创建API,例如jQuery UI API.因此,您可以访问类似以下的插件方法:

Think about refactoring your plugin using object oriented code. With this you can make API for your plugins like jQuery UI API. So you could access to plugin methods like:

$('select').customSelect(); // apply plugin to elements
$('select').customSelect('resetOpacity'); // call method resetOpacity();
$('select').customSelect('setOpacity', 0.5); // call method with arguments

用于创建此类插件的基本模板如下所示:

Basic template for creating such plugins will look like following:

// plugin example
(function($){
    // custom select class
    function CustomSelect(item, options) {
        this.options = $.extend({
            foo: 'bar'
        }, options);
        this.item = $(item);
        this.init();
    }
    CustomSelect.prototype = {
        init: function() {
            this.item.css({opacity:0.5});
        },
        resetOpacity: function() {
            this.setOpacity('');
        },
        setOpacity: function(opacity) {
            this.item.css({opacity:opacity});
        }
    }

    // jQuery plugin interface
    $.fn.customSelect = function(opt) {
        // slice arguments to leave only arguments after function name
        var args = Array.prototype.slice.call(arguments, 1);
        return this.each(function() {
            var item = $(this), instance = item.data('CustomSelect');
            if(!instance) {
                // create plugin instance and save it in data
                item.data('CustomSelect', new CustomSelect(this, opt));
            } else {
                // if instance already created call method
                if(typeof opt === 'string') {
                    instance[opt].apply(instance, args);
                }
            }
        });
    }

}(jQuery));

// plugin testing
$('select').customSelect();

正在工作的JS拨弄这里: http://jsfiddle.net/XsZ3Z/

Working JS fiddle here: http://jsfiddle.net/XsZ3Z/

这篇关于jQuery插件创建和面向公众的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆