People, I confess honestly: I did not understand anything at all in creating plug-ins for jquery. I am ashamed, but need to be corrected. In the topic of multiplicity-values-in-input, I created the insides of a method for changing input . Tell me, please, how to turn this into

$("SELECTOR").correct_value(quantity_per_pack); 

To work with any input.

    1 answer 1

    Look at the link , make out a couple of plugins. If it turns out a little, I will try to paint in more detail. =)

    Added by

     <p class="myFuncted">eeeee</p> <p>eeeee</p> <p class="myFuncted">eeeee</p> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <script> jQuery.fn.myFunction = function(options){ // пишем через jQuery, чтобы можно было переопределить через noConflict() var opts = jQuery.extend({ // тут идут значения по умолчанию // если в объекте options что-то не было передано, оно подтянется из этого объекта param1: 'value1', param2: 'value2' }, options); // ок, объединили значения объектов. все теперь хранится в объекте opts return this.each(function(){ // бежим по всем элементам выборки jQuery // а тут идет код плагина // this - конкретный элемент, с которым работаем // opts мы заранее сформировали со всеми необходимыми параметрами var t = $(this); t.data('params', opts.param1+' '+opts.param2); }); // return нужен для совместимости }; $('.myFuncted').myFunction({param1: 'value_not_1'}).css('color', 'red').click(function(){alert($(this).data('params'));}); // вызов плагина. из-за return this.each можно применять эффекты в цепочке </script> 

    Added more
    1) Through $ will work too. But for compatibility with other libraries, it's better to use jQuery ($ is an alias, you can override it).
    2) var opts = jQuery.extend(defObj, options); From defObj jQuery itself pulls the key pairs: the value in options, if there are no such keys in options. The opts properties are accessed via opts.param or opts ['param'].
    3) options is set when the function is called, and defObj is written by the developer. All parameters are optional, but if your plug-in will not work without any of them, they will have to be set in defObj.

    • 1) we write through jQuery // through $ will work too? Why not the other way around? 2) it will be tightened from this object - in what form? For example, the value attribute is opts.val () or this.val ()? 3) How to indicate that the parameter is required / optional? Analog in PHP: function myfunc ($ var1, $ var2 = 'abc'); var2 is an optional parameter. Or standard javascript methods through arguments? - knes
    • More added. - ling