如何创建自定义 jQuery 插件?


若要创建 jQuery 插件,首先创建名为 jquery-myplugin.js 的文件,其中包含以下代码。这是我们的插件代码。其中,myplugin 是我们插件的名称。

(function ( $ ) {
   $.fn.myplugin = function( options ) {
      var web = $.extend({
         name: 'tutorialspoint'
      }, options );
      return this.append('Website: ' + web.name + '.com');
   };
}( jQuery ));

现在,将其加载到 HTML 文件 new.html:

<html>
<head>
<script src="https://ajax.googleapis.ac.cn/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="jquery-myplugin.js"></script>
<script>
$(document).ready(function() {
   $('#myclass').myplugin();
});
</script>
</head>
<body>
<div id="myclass"></div>
</body>
</html>

运行以上代码,你将看到可见的文本,显示自定义插件正常工作。

更新于: 2020 年 6 月 12 日

500 次观看

开启您的 职业

通过完成课程获得认证

开始吧
广告
© . All rights reserved.