简体   繁体   中英

Writing a simple plugin/component


I want to write a component(or plugin) like that.
when i write:
var a = new myPluginName ('#myElement', { bla:bla});
or

$('#myElement').myPluginName();

It must create two input. Thats all. How can i do this? Can you give me an example like that? Or any idea will be helpful.

In other words, my goal is create two input with my component.
Thank you.

You can create custom jQuery plugin like this:

(function($){
 $.fn.extend({ 
     //plugin name - inpuX
     inputX: function(options) {
        var defaults = {
            width: 200,
            defaultPadding: 2,
            border: '2px solid red'
        };

        var options = $.extend(defaults, options);

        return this.each(function() {
              var o =options;
              var obj = $(this);                             

              $(obj)
                  .css('padding', o.defaultPadding)
                  .css('width', o.width)
                  .css('border', o.border)
                  .css('display', 'block');  
        });
    }
});
})(jQuery);

and then call it like this:

 $('#inputA').inputX({width: 150, defaultPadding:5, border: '1px dashed black'});
 $('#inputB').inputX({width: 200, defaultPadding:10});  

on elements in html:

<input id="inputA" type="text" />
<input id="inputB" type="text" />

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