要从外部调用jQuery插件内部的函数,请尝试运行以下代码。该代码以jQuery为例使用属性更新名称:
<html> <head> <script src = "https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script> <script> $.fn.person = function(prop) { var defaults = $.extend({ name: 'Amit' }, prop); //在插件之外使用的方法 var person = { changeName: function(name) { defaults.name = name; }, getName: function() { return defaults.name; } }; return person; }; //设置初始属性 var person = $('#person').person({ name: 'Sachin' }); document.write('Initial name of person: ', person.getName()); person.changeName('Amit'); //打印新名称 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!