Подтвердить что ты не робот

Как добавить функцию в jQuery?

Какой самый простой способ определить новую функцию члена jQuery ?

Чтобы я мог вызвать что-то вроде:

$('#id').applyMyOwnFunc()
4b9b3361

Ответ 1

Пожалуйста, смотрите Определение ваших собственных функций в jQuery:

В этом посте я хочу представить, как легко определить свои собственные функции в jQuery и как их использовать.

Из поста:

jQuery.fn.yourFunctionName = function() {
    var o = $(this[0]) // This is the element

    return this; // This is needed so other functions can keep chaining off of this
};

Просто используйте:

$(element).yourFunctionName();

Ответ 2

Это шаблон, который я предпочитаю определять мои собственные плагины.

(function($) {

    $.fn.extend({
        myfunc: function(options) {
            options = $.extend( {}, $.MyFunc.defaults, options );

            this.each(function() {
                new $.MyFunc(this,options);
            });
            return this;
        }
    });

    // ctl is the element, options is the set of defaults + user options
    $.MyFunc = function( ctl, options ) {
         ...your function.
    };

    // option defaults
    $.MyFunc.defaults = {
        ...hash of default settings...
    };

})(jQuery);

Применяется как:

$('selector').myfunc( { option: value } );

Ответ 3

Документация jquery содержит раздел создание плагинов, где я нашел этот пример:

jQuery.fn.debug = function() {
  return this.each(function(){
    alert(this);
  });
};

Тогда вы сможете называть это следующим образом:

$("div p").debug();

Ответ 4

jQuery имеет функцию extend, чтобы сделать это

jQuery.fn.extend({
  check: function() {
    return this.each(function() { this.checked = true; });
  },
  uncheck: function() {
    return this.each(function() { this.checked = false; });
  }
});

вы можете увидеть документацию там

Ответ 5

Вот плагин, в нем простейшая форма...

jQuery.fn.myPlugin = function() {
  // do something here
};

Вы действительно захотите проконсультироваться с документацией:

http://docs.jquery.com/Plugins/Authoring

Ответ 6

/* This prototype example allows you to remove array from array */

Array.prototype.remove = function(x) {
var i;
for(i in this){
    if(this[i].toString() == x.toString()){
        this.splice(i,1)
    }
  }
 }


----> Now we can use it like this :

var val=10;
myarray.remove(val);