我知道在JavaScript中语法是这样的:
function myfunction(param){
//some code
}
是否有一种方法可以在jQuery中声明一个可以添加到元素中的函数?例如:
$('#my_div').myfunction()
我知道在JavaScript中语法是这样的:
function myfunction(param){
//some code
}
是否有一种方法可以在jQuery中声明一个可以添加到元素中的函数?例如:
$('#my_div').myfunction()
当前回答
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Define a function in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function() {
$.fn.myFunction = function() {
alert('You have successfully defined your function!');
}
$(".call-btn").click(function(){
$.fn.myFunction();
});
});
</script>
</head>
<body>
<button type="button" class="call-btn">Click Here</button>
</body>
</html>
其他回答
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Define a function in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function() {
$.fn.myFunction = function() {
alert('You have successfully defined your function!');
}
$(".call-btn").click(function(){
$.fn.myFunction();
});
});
</script>
</head>
<body>
<button type="button" class="call-btn">Click Here</button>
</body>
</html>
要使一个函数在jQuery对象上可用,你需要将它添加到jQuery原型中(fn是jQuery原型的快捷方式),如下所示:
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插件。
例如—http://jsfiddle.net/VwPrm/
你可以编写自己的jQuery插件(可以在选定的元素上调用的函数),如下所示:
(function( $ ){ $.fn.myFunc = function(param1, param2){ //this - jquery object holds your selected elements } })( jQuery );
稍后调用它:
$('div').myFunc(1, null);
是的,你所描述的是一个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。
听起来好像你想通过jQuery的原型(也就是写一个jQuery插件)来扩展jQuery对象。这意味着通过调用jQuery函数($(selector/DOM element))创建的每个新对象都有这个方法。
这里有一个非常简单的例子:
$.fn.myFunction = function () {
alert('it works');
};
Demo