我正在搜索有关的信息 - "如何创建自定义(自己的)JQuery函数以及如何使用它"
我在谷歌搜索过,但我没有找到相关信息.
你能详细解释一下自定义功能吗?
Jam*_*ice 59
通过"自定义功能"我假设你的意思是"插件".如果是这样的话,jQuery网站上有一个很好的教程.基本的想法是这样的:
(function($) {
$.fn.myPlugin = function() {
return this.each(function() {
//Do stuff
});
};
}(jQuery));
Run Code Online (Sandbox Code Playgroud)
基本上,上面的代码做了一些事情.首先,它捕获了它的值jQuery并将其传递给一个匿名函数,然后可以将其称为$(这样,您的插件的用户恰好使用$其他东西的标识符仍然可以使用它.)
然后它声明一个方法on $.fn,它只是一个别名$.prototype.在该方法中,this指的是已调用插件的匹配元素集.既然这是一个jQuery对象,并且可能包含多个元素,则需要迭代该集合(这就是为什么each存在).
该return语句用于维护插件与其他jQuery方法的可链接性.由于each返回了一个jQuery实例,插件本身返回一个jQuery实例,显然可以在jQuery实例上调用其他jQuery方法.
小智 6
正如gesutery所说,使用extend().您可以将自己的属性和函数添加为值:
$(function(){
$.extend({
propAsString: '',
propAsNumber: 12345,
propAsObject: {},
propAsFunction: function() {
//your function code
}
});
$.propAsFunction(); //call your function
});
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它
$(document).ready(function() {
$('#button').click(function(){
$(this).myFunction();
});
$.fn.myFunction = function() {
alert('test');
}
});
Run Code Online (Sandbox Code Playgroud)
小智 5
(function($){
$.fn.extend({
//plugin name - animatemenu
animateMenu: function(options) {
//Settings list and the default values
var defaults = {
animatePadding: 60,
defaultPadding: 10,
evenColor: '#ccc',
oddColor: '#eee'
};
var options = $.extend(defaults, options);
return this.each(function() {
var o =options;
//Assign current element to variable, in this case is UL element
var obj = $(this);
//Get all LI in the UL
var items = $("li", obj);
//Change the color according to odd and even rows
$("li:even", obj).css('background-color', o.evenColor);
$("li:odd", obj).css('background-color', o.oddColor);
//Attach mouseover and mouseout event to the LI
items.mouseover(function() {
$(this).animate({paddingLeft: o.animatePadding}, 300);
}).mouseout(function() {
$(this).animate({paddingLeft: o.defaultPadding}, 300);
});
});
}
});
})(jQuery);
Run Code Online (Sandbox Code Playgroud)