【发布时间】:2009-11-20 03:25:04
【问题描述】:
定义新的 jQuery 成员函数最简单的方法是什么?
所以我可以这样称呼:
$('#id').applyMyOwnFunc()
【问题讨论】:
标签: jquery
定义新的 jQuery 成员函数最简单的方法是什么?
所以我可以这样称呼:
$('#id').applyMyOwnFunc()
【问题讨论】:
标签: jquery
请看Basil Goldman的“Defining your own functions in jQuery”:
在这篇文章中,我想介绍如何 轻松定义自己的函数 jQuery 和使用它们。
根据上面链接的博文中的代码进行了修改:
jQuery.fn.yourFunctionName = function() {
// `this` is the jQuery Object on which the yourFunctionName method is called.
// `arguments` will contain any arguments passed to the yourFunctionName method.
var firstElement = this[0];
return this; // Needed for other methods to be able to chain off of yourFunctionName.
};
只需使用:
$(element).yourFunctionName();
【讨论】:
extend() 函数... RageZ 的答案给出了我认为正确的答案。
this 指的是 jQuery 对象,在这种情况下它的长度是 1,因为选择器是一个 ID,应该是唯一的。然后使用this[0] 获取HTMLElement。然后用$(this[0]) 将它重新包装在jQuery 中。为什么?
这是我更喜欢定义自己的插件的模式。
(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 } );
【讨论】:
new $.MyFunc($(this),options);
jquery documentation 有一个关于 plugin authoring, 的部分,我在其中找到了这个示例:
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; });
}
});
您可以查看文档there
【讨论】:
这是一个插件,最简单的形式...
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);
【讨论】: