在具有类似配置的多个目标和页面上使用jQuery插件

时间:2014-10-13 16:30:43

标签: javascript jquery

我已成功配置了一个jQuery插件,如下所示(编辑:请注意,我不是要求任何人查看,只是回答具体问题)。现在我需要使用相同的配置对象对不同的目标执行相同的操作,除了第4行的ID名称(即代替template1,它可能是someOtherTemplateID

如何在不重复每页的代码的情况下这样做?

我唯一的想法是创建一个对象,其中包含一切传递给下面插件的对象,但还包括一个名为template的额外属性。然后,我将其更改为var source = $("#template1").html();,而不是硬编码var source = $("#"+this.template).html();,然后设置myObj.template="someOtherTemplateID",并将插件用作$('a.linkPreview').ajaxTip(myObj);。这种方法听起来并不理想,我希望有一种更清洁的方法。

$('a.linkPreview').ajaxTip({
    url:'index.php',
    display: function(d){
        var source = $("#template1").html();  //template1 needs to change to another ID 
        var template = Handlebars.compile(source); 
        Handlebars.registerHelper("formatPhoneNumber", function(p) {
            p = p.toString();
            return "(" + p.substr(0,3) + ") " + p.substr(3,3) + "-" + p.substr(6,4);
        });
        Handlebars.registerHelper('fullName', function(f,l) {
            return f + ((f&&l)?" ":"") + l;
        });
        Handlebars.registerHelper('specNumber', function(s) {
            return (s)?s.substr(0,2)+' '+s.substr(2,2)+' '+s.substr(4):'';
        });
        Handlebars.registerHelper('specNumberP', function(s) {
            return (s)?' ('+s.substr(0,2)+' '+s.substr(2,2)+' '+s.substr(4)+')':'';
        });
        return template(data);
    },
    getData:function(){
        var d=ayb.getUrlVars(this.attr('href'));
        d.task='getPopup';
        return d;
    }
});

下面列出了ajaxTip插件。请注意,我不相信我的问题。

/*
* jQuery ajaxTip
* Copyright Michael Reed, 2013
* Dual licensed under the MIT and GPL licenses.
*/
(function($){
    var defaults = {
        'url'      : 'getAjaxTip.php', // The url used to get the tooltip data.
        'class'    : '', // Css class(es) to add to tooltip (along with standardAjaxTip).
        'mouseMove': true, // A flag indicating whether to move tooltip with mouse.
        'speed'    : 'fast', // The speed at which to fade in the tool tip.
        'delay'    : 250, // Delay (in ms) before requesting data from server.
        'xOffset'  : 20,
        'yOffset'  : 10,
        'dataType' : 'json',            
        'getData'  : function () {  //Use to set additional data to the server 
            return {}; 
        },
        // A function to transform the data from the server into an html fragment.
        'display'  : function(data) {   
            var htmlString = '';
            $.each(data, function (key, val) {
                htmlString += '<p>' + val + '</p>';
            });
            return htmlString;
        }
    };

    var methods = {
        init : function (options) {
            // Create settings using the defaults extended with any options provided.
            var settings = $.extend({}, defaults, options);

            return this.each(function () {
                var title,
                    timeoutID,
                    ajax,
                    $t,
                    ajaxTip;

                // Wrap the content of the current element in a span.
                $t = $(this).wrapInner('<span />');

                $t.children('span').hover(function(e) {
                    if(!$t.hasClass('ajaxToolActive')) {
                        title = $t.attr('title');
                        $t.attr('title','');  // Remove the title so that it doesn't show on hover.

                        timeoutID = window.setTimeout(function () {
                            ajax = $.get(settings.url, settings.getData.call($t), function (data) {
                                // Create a div to be the tooltip pop up, add the styling as well as
                                // the html (from the display function) to it and then fade the element in
                                // using the speed specified in the settings.
                                ajaxTip = $('<div />')
                                .addClass('standardAjaxTip ' + settings['class'])
                                .html(((title !== '') ? '<h3>' + title + '</h3>' : '') + settings.display.call($t,data))
                                .css('top', (e.pageY - settings.yOffset) + 'px')
                                .css('left', (e.pageX + settings.xOffset) + 'px')
                                .css('position', 'absolute')
                                .appendTo('body')
                                .fadeIn(settings.speed);

                                $t.addClass('ajaxToolActive');
                            }, 
                            settings.dataType);
                        }, settings.delay);
                    }
                },
                function () {
                    // User is no longer hovering so cancel the call to the server and hide the tooltip.
                    if (typeof ajax === 'object') { 
                        ajax.abort(); 
                    }
                    window.clearTimeout(timeoutID);
                    $t.attr('title', title);

                    if ($t.hasClass('ajaxToolActive')) {
                        ajaxTip.remove();
                        $t.removeClass('ajaxToolActive');
                    }
                });

                $t.mousemove(function (e) {
                    if (settings.mouseMove && $t.hasClass('ajaxToolActive')) {
                        ajaxTip.css('top', (e.pageY - settings.yOffset) + 'px')
                            .css('left', (e.pageX + settings.xOffset) + 'px');
                    }
                });
            });
        },
        destroy : function () {
            return this.each(function () {
                var $e = $(this);
                $e.html($e.children('span').html());
            });
        }
    };

    $.fn.ajaxTip = 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.ajaxTip');
        }    
    };
}(jQuery));

1 个答案:

答案 0 :(得分:0)

试一试。你用$(“selector”)来调用它.ajaxTip(“templateIdHere”);

(function($) {
    // add object to vars with a placeholder for target
    var defaultObject = {
        target: null, // the target later gets passed in here
        url: 'index.php',
        display: function(data, target) {
            var source = $('#' + target).html();
            /* ... */
        },
        /* ... */
    };

    /* ... */

    .html(((title !== '') ? '<h3>' + title + '</h3>' : '') + settings.display.call($t,data, settings.target))

    /* ... */

    $.fn.ajaxTip = function(method) {
        if (methods[method]) {
            /* ... */
        } else if (typeof method === 'string') {
             return methods.init.call(this, $.extend(defaultObject, {target: method}));
        } else if (typeof method === 'object' || ! method) {
            /* ... */
        } else {
            /* ... */
        }    
    };
}(jQuery));

有一个限制:必须在此插件之前定义全局对象Handlebars