jQuery插件开发详细教程

2020-05-23 06:07:12易采站长站整理

        },
        hide: function () {
            //…
        },
        update: function (content) {
            //…
        }
    };
    $.fn.tooltip = 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 + ‘ does not exist on jQuery.tooltip’);
        }
    };
})(jQuery);
$(‘#fun’).tooltip();
//一段时间之后… …
$(‘#fun’).tooltip(‘destroy’);


在这个例子中,当tooltip通过init方法初始化时,它将reposition方法绑定到resize事件并给reposition非那方法赋予命名空间通过追加.tooltip。 稍后, 当开发人员需要销毁tooltip的时候,我们可以同时解除其中reposition方法和resize事件的绑定,通过传递reposition的命名空间给插件。 这使我们能够安全地解除事件的绑定并不会影响到此插件之外的绑定。


九、数据


通常在插件开发的时候,你可能需要记录或者检查你的插件是否已经被初始化给了一个元素。 使用jQuery的data方法是一个很好的基于元素的记录变量的途径。尽管如此,相对于记录大量的不同名字的分离的data,  使用一个单独的对象保存所有变量,并通过一个单独的命名空间读取这个对象不失为一个更好的方法。

(function ($) {
    var methods = {
        init: function (options) {
            return this.each(function () {
                var $this = $(this),
                    data = $this.data(‘tooltip’),
                    tooltip = $(‘<div />’, {
                        text: $this.attr(‘title’)