我知道在JavaScript中,语法如下:
function myfunction(param){
//some code
}
有没有办法在jQuery中声明一个可以添加到元素中的函数?例如:
$('#my_div').myfunction()
发布于 2012-08-23 21:59:27
从Docs
(function( $ ){
$.fn.myfunction = function() {
alert('hello world');
return this;
};
})( jQuery );
然后你就做了
$('#my_div').myfunction();
发布于 2012-08-23 22:00:00
要使某个函数在jQuery对象上可用,可以将其添加到jQuery原型(fn是jQuery中prototype的快捷方式),如下所示:
jQuery.fn.myFunction = function() {
// Usually iterate over the items and return for chainability
// 'this' is the elements returns by the selector
return this.each(function() {
// do something to each item matching the selector
}
}
这通常称为jQuery plugin。
发布于 2012-08-23 21:58:19
$(function () {
//declare function
$.fn.myfunction = function () {
return true;
};
});
$(document).ready(function () {
//call function
$("#my_div").myfunction();
});
https://stackoverflow.com/questions/12093192
复制相似问题