在 jQuery 中定义函数与 JavaScript 不同,语法完全不同。函数是一组接受输入、进行特定计算并产生输出的语句。基本上,函数是一组执行某些特定任务或进行某些计算然后将结果返回给用户的语句。
这个想法是将一些常见或重复完成的任务放在一起并创建一个函数,这样我们就可以调用该函数,而不是为不同的输入一次又一次地编写相同的代码。
句法:
$.fn.myFunction = function(){}
复制
下面的例子说明了 jQuery 中的函数定义:
示例 1:
<!DOCTYPE html> <html> <head> <title> How to Define jQuery function ? </title> <script src= "https://code.jquery.com/jquery-1.12.4.min.js"> </script> <script> $(document).ready(function () { $.fn.myFunction = function () { document.getElementById("geeks").innerHTML = "JQuery function is defined!"; } $(".gfg").click(function () { $.fn.myFunction(); }); }); </script> </head> <body style="text-align:center"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Defining function in jQuery </h3> <p id="geeks"></p> <button type="button" class="gfg"> Click </button> </body> </html>
复制
输出:
示例 2:
<!DOCTYPE html> <html> <head> <title> How to Define jQuery function ? </title> <script src= "https://code.jquery.com/jquery-1.12.4.min.js"> </script> <script> $(document).ready(function () { $.fn.myFunction = function () { alert('JQuery function is defined!'); } $(".gfg").click(function () { $.fn.myFunction(); }); }); </script> </head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksforGeeks </h1> <h3> Defining function in jQuery </h3> <button type="button" class="gfg"> Click </button> </body> </html>
复制
输出: