简体   繁体   中英

Creating a Dynamic JQuery Plugin

I am learning about creating JQuery Plugins. Currently, I have a plugin that is defined as follows:

(function ($) {
    $.fn.myPlugin = function (options) {
        var defaults = { e: 0 },
        settings = $.extend({}, defaults, options);

        var plugin = $.myPlugin.getHtml(options.e);
        if ((plugin != null) && (plugin != undefined) && (plugin.length > 0)) {
            this.html(plugin);
        }
    };

    $.myPlugin = {
        getHtml: function (e) {
            var s = "";
            if (e == 0) {
              s = "1";
            } else {
              s = "2";
            }
            return s;
        }
    };
})(jQuery);

Currently, I initialize an instance of this plugin using the following:

$("#myDiv").myPlugin({ e: 0 });

How do I add a timer to myPlugin so that every 15 seconds I can update the html of myDiv with a counter?

Thank you!

Here is a quick bit of code that you could put within the plugin to run setInterval as suggested by the comment above. Adapt for your purposes. Lookup setInterval for more info.

var counter = 0;
setInterval(function () {
   counter += 1;
   $.myPlugin.getHtml(counter)
}, 15000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM