如何在外部调用 jQuery 插件中的函数?
若要从外部调用 jQuery 插件中的函数,请尝试运行以下代码。此代码使用属性来更新jQuery的名称,例如
<html> <head> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $.fn.person = function(prop) { var defaults = $.extend({ name: 'Amit' }, prop); // methods to be used outside of the plugin var person = { changeName: function(name) { defaults.name = name; }, getName: function() { return defaults.name; } }; return person; }; // set initial properties var person = $('#person').person({ name: 'Sachin' }); document.write('Initial name of person: ', person.getName()); person.changeName('Amit'); // printing new name document.write('<br>Changed name of person: ', person.getName()); </script> </head> <body> <div id = "person">Changes done above!</div> </body> </html>
输出
Initial name of person: Sachin Changed name of person: Amit Changes done above!
广告