我知道在JavaScript中语法是这样的:
function myfunction(param){
//some code
}
是否有一种方法可以在jQuery中声明一个可以添加到元素中的函数?例如:
$('#my_div').myfunction()
我知道在JavaScript中语法是这样的:
function myfunction(param){
//some code
}
是否有一种方法可以在jQuery中声明一个可以添加到元素中的函数?例如:
$('#my_div').myfunction()
当前回答
虽然有大量的文档/教程,但你的问题的简单答案是:
// to create a jQuery function, you basically just extend the jQuery prototype
// (using the fn alias)
$.fn.myfunction = function () {
// blah
};
在该函数中,this变量对应于调用函数的jQuery包装集。比如:
$.fn.myfunction = function () {
console.log(this.length);
};
$('.foo').myfunction();
... 将类foo的元素数量刷新到控制台。
当然,语义方面还有更多的东西(以及最佳实践等),所以一定要仔细阅读。
其他回答
$(function () {
//declare function
$.fn.myfunction = function () {
return true;
};
});
$(document).ready(function () {
//call function
$("#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>
虽然有大量的文档/教程,但你的问题的简单答案是:
// to create a jQuery function, you basically just extend the jQuery prototype
// (using the fn alias)
$.fn.myfunction = function () {
// blah
};
在该函数中,this变量对应于调用函数的jQuery包装集。比如:
$.fn.myfunction = function () {
console.log(this.length);
};
$('.foo').myfunction();
... 将类foo的元素数量刷新到控制台。
当然,语义方面还有更多的东西(以及最佳实践等),所以一定要仔细阅读。
创建一个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*/}