Какой самый простой способ определить новую функцию члена jQuery ?
Чтобы я мог вызвать что-то вроде:
$('#id').applyMyOwnFunc()
Какой самый простой способ определить новую функцию члена jQuery ?
Чтобы я мог вызвать что-то вроде:
$('#id').applyMyOwnFunc()
Пожалуйста, смотрите Определение ваших собственных функций в 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();
Это шаблон, который я предпочитаю определять мои собственные плагины.
(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 } );
Документация jquery содержит раздел создание плагинов, где я нашел этот пример:
jQuery.fn.debug = function() {
return this.each(function(){
alert(this);
});
};
Тогда вы сможете называть это следующим образом:
$("div p").debug();
jQuery имеет функцию extend
, чтобы сделать это
jQuery.fn.extend({
check: function() {
return this.each(function() { this.checked = true; });
},
uncheck: function() {
return this.each(function() { this.checked = false; });
}
});
вы можете увидеть документацию там
Вот плагин, в нем простейшая форма...
jQuery.fn.myPlugin = function() {
// do something here
};
Вы действительно захотите проконсультироваться с документацией:
/* 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);