我知道在JavaScript中语法是这样的:
function myfunction(param){
//some code
}
是否有一种方法可以在jQuery中声明一个可以添加到元素中的函数?例如:
$('#my_div').myfunction()
我知道在JavaScript中语法是这样的:
function myfunction(param){
//some code
}
是否有一种方法可以在jQuery中声明一个可以添加到元素中的函数?例如:
$('#my_div').myfunction()
当前回答
你可以这样做:
jQuery.fn.extend({
myfunction: function(param){
// code here
},
});
OR
jQuery.extend({
myfunction: function(param){
// code here
},
});
$(element).myfunction(param);
其他回答
是的,你所描述的是一个jQuery插件。
要编写jQuery插件,您需要在JavaScript中创建一个函数,并将其分配给对象jQuery.fn的属性。
E.g.
jQuery.fn.myfunction = function(param) {
// Some code
}
在插件函数中,this关键字被设置为调用插件的jQuery对象。所以,当你这样做的时候:
$('#my_div').myfunction()
然后myfunction内部的这个将被设置为$('#my_div')返回的jQuery对象。
详情请见http://docs.jquery.com/Plugins/Authoring。
创建一个colorize方法:
$.fn.colorize = function custom_colorize(some_color) {
this.css('color', some_color);
return this;
}
使用它:
$('#my_div').colorize('green');
这个简单的例子结合了如何在jQuery文档中创建一个基本的插件,以及来自@Candide, @Michael的回答。
命名函数表达式可以改善堆栈跟踪等。 返回此值的自定义方法可能是链式的。(谢谢@Potheek。)
用jQuery创建函数最简单的例子是
jQuery.fn.extend({
exists: function() { return this.length }
});
if($(selector).exists()){/*do something here*/}
$(function () {
//declare function
$.fn.myfunction = function () {
return true;
};
});
$(document).ready(function () {
//call function
$("#my_div").myfunction();
});
听起来好像你想通过jQuery的原型(也就是写一个jQuery插件)来扩展jQuery对象。这意味着通过调用jQuery函数($(selector/DOM element))创建的每个新对象都有这个方法。
这里有一个非常简单的例子:
$.fn.myFunction = function () {
alert('it works');
};
Demo