如何创建自定义 jQuery 插件?

jqueryweb developmentfront end technology更新于 2026/2/10 11:07:17

要创建 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.com/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>

运行以上代码,您可以看到文本可见,这表明您的自定义插件正常运行。


相关文章