JQuery Plugin 开发

学习 JQuery 插件开发之后, 可以将自己平时常用的功能封装成插件, 便于在不同的项目之间使用.

JQuery 官网上的 插件开发教程就很不错, 简单易懂.

jquery 中有2个重要的API是和插件编写相关的.

  1. jQuery.extend(object)    即 $.extend(object)
  2. jQuery.fn.extend(object) 即 $.fn.extend(object)

 

这2个API都是为了将自己编写的功能以插件的形式加入到 jquery 中.

但是含义上是有区别的.

1.1 $.extend(object)

这个函数是用来扩展 jQuery 本身, 也就是扩展 "$" 的.

示例如下:

复制代码
<!DOCTYPE HTML>
<html>
    <head>
        <title>jquery plugin test</title>
        <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
        <script type="text/javascript">
          $(function(){
              
              $("#btn-extend").click(function(){
                  $.extend({
                      test: function(a) { alert(a); },
                  });
              });

              $("#btn-test").click(function(){
                  if ($.test)
                      $.test("test");
                  else
                      alert("不存在 $.test 方法!");
              });
          });
        </script>
    </head>
    <body>
        <button id="btn-test">测试 $.test() </button>
        <button id="btn-extend">扩展 $ 本身 </button>
    </body>
</html>
复制代码

 

首先点击 [btn-test] 按钮, 提示没有 test 方法, 然后点击 [btn-extend] 按钮, 扩展 $ 本身.

再次点击 [btn-test] 按钮, 执行扩展的 $.test() 函数.

 

1.2 $.fn.extend(object)

这个函数用来为 jQuery 对象提供新的方法.

所谓 jQuery 对象, 最常见的我们平时通过jQuery选择器获取的对象, 比如: $("#id"), $(".class") 等等.

复制代码
<!DOCTYPE HTML>
<html>
    <head>
        <title>jquery plugin test</title>
        <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
        <script type="text/javascript">
          $(function(){
              
              $("#btn-extend").click(function(){
                  $.fn.extend({
                      test: function(a) { alert(a); },
                  });
              });

              $("#btn-test").click(function(){
                  if ($(this).test)
                      $(this).test($(this).attr("id"));
                  else
                      alert("不存在 test 方法!");
              });
          });
        </script>
    </head>
    <body>
        <button id="btn-test">测试 $(this).test() </button>
        <button id="btn-extend">扩展 jQuery($) 对象 </button>
        
    </body>
</html>
复制代码

首先点击 [btn-test] 按钮, 提示没有 test 方法, 然后点击 [btn-extend] 按钮, 扩展 $ 对象.

再次点击 [btn-test] 按钮, 执行扩展的 $.fn.test() 函数.

 

编写 jQuery 插件之前, 一定要弄懂 "$ 本身" 和 "$ 对象" 的区别. ($ 就是 jQuery)

也就是弄懂 $.extend 和 $.fn.extend 之间的区别.

 

2. UI相关的插件

一般来说, 纯UI相关的插件很少, 都是UI和功能一起配合使用的, 比如 jQuery UI 库.

下面的示例主要为了说明如何使用 jQuery 插件, 所以只和UI相关.

 

2.1 示例1 : 统一设置颜色

示例 HTML:

复制代码
<!DOCTYPE HTML>
<html>
    <head>
        <title>jquery plugin test</title>
        <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
        <script type="text/javascript" src="js/jquery-plugin.js"></script>
        <script type="text/javascript">
          $(function(){
              $("#btn-plugin").click(function(){
                  $(".smalldiv").toggle_back();
              });
          });

        </script>
        <style type="text/css" media="screen">
            
          .bigdiv {
            width: 500px;
            height:100px;
          }

          .smalldiv {
              width: 50px;
              height: 50px;
              background-color: green;
              float:left;
          }
        </style>
    </head>
    <body>
        <button id="btn-plugin">执行插件</button>
        <div class="bigdiv">
            <div class="smalldiv red">
                1
            </div>
            <div class="smalldiv green">
                2
            </div>
            <div class="smalldiv red">
                3
            </div>
            <div class="smalldiv green">
                4
            </div>
            <div class="smalldiv red">
                5
            </div>
            <div class="smalldiv green">
                6
            </div>
            <div class="smalldiv red">
                7
            </div>
            <div class="smalldiv green">
                8
            </div>
            <div class="smalldiv red">
                9
            </div>
            <div class="smalldiv green">
                10
            </div>
        </div>
        
    </body>
</html>
复制代码

 

示例 jQuery 插件:

复制代码
/* jquery plugin for test
 * filename: jquery-plugin.js
 */

// 下面的格式也是 jQuery 插件的常用写法
(function ($) {
    $.fn.toggle_back = function() {
        if (this.css("background-color") == "rgb(255, 0, 0)")
            this.css("background-color", "green");
        else
            this.css("background-color", "red");
    };
}(jQuery));
复制代码

通过点击 html 页面上的按钮, 可以切换所有 smalldiv 的背景色.

 

2.2 示例2 : 分别设置颜色

这个例子比上面那个略微复杂一些, 上面的示例1 是对所有 smalldiv 统一设置背景色, 不够灵活.

这个示例通过 jQuery 的 $.fn.each 函数根据每个 smalldiv 的 class 分别设置背景色.

(HTML部分的代码和示例1 一样)

复制代码
/* jquery plugin for test
 * filename: jquery-plugin.js
 */

// 下面的格式也是 jQuery 插件的常用写法
(function ($) {
    $.fn.toggle_back = function() {
        this.each(function() {
            var div = $(this);
            if (div.hasClass("red")) {
                div.removeClass("red");
                div.addClass("green");
                div.css("background-color", "green");
            }
            else {
                div.removeClass("green");
                div.addClass("red");
                div.css("background-color", "red");
            }
        });
        return this;
    };
}(jQuery));
复制代码

 

这里需要注意2个地方:

1. 代码中 this 的含义

this.each(function() {

这里的 this 是jQuery 对象, 也就是通过 $("#id"), $(".class") 之类的选择器获取的对象.

*注意* 这个 this 的位置是在 $.fn.toggle_back 的主函数体中.

 

var div = $(this);

这里的 this 是 DOM 对象, 所以通过 $(this) 才能变成 jQuery 对象.

至于为什么 each 中的this就是各个 DOM 对象, 那是因为 each 的实现中将 jQuery 对象转换为了 DOM 对象.

 

2. 插件代码最后的 return this;

这里之所以要 return this; 是为了实现 jQuery 的链式表达式. 也就是 return this; 之后, 可以接着调用其他 jQuery 函数.

比如 $(".class").toggle_back().css("color", "red");

上面的示例2中 $("#btn-plugin").click 函数可以改为如下:

$("#btn-plugin").click(function(){
     $(".smalldiv").toggle_back().css("color", "red");
});

 

3. 功能型插件

下面通过一个 日期转换 的例子, 说明功能型插件的写法.

HTML 部分:

复制代码
<!DOCTYPE HTML>
<html>
    <head>
        <title>jquery plugin test</title>
        <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
        <script type="text/javascript" src="js/jquery-plugin.js"></script>
        <script type="text/javascript">
          $(function(){
              $("#btn-plugin").click(function(){
                  $("h2").dt_format(new Date());
              });
          });

        </script>
    </head>
    <body>
        <button id="btn-plugin">显示格式化的时间</button>
        <hr />
        <h1>当前时间:</h1>
        <h2 class="date">nothing</h2>
        <h2 class="time">nothing</h2>
        <h2 class="datetime">nothing</h2>
    </body>
</html>
复制代码

 

插件 js 只是简单的转换了一时间格式, 仅仅为了演示:

复制代码
/* jquery plugin for test
 * filename: jquery-plugin.js
 */

(function ($) {

    $.fn.dt_format = function(dt) {
        this.each(function(){
            var elem = $(this);
            if (elem.hasClass("date"))
                elem.text($.fn.dt_format.date(dt));
            if (elem.hasClass("time"))
                elem.text($.fn.dt_format.time(dt));
            if (elem.hasClass("datetime"))
                elem.text($.fn.dt_format.datetime(dt));
        });
        return this;
    };

    $.fn.dt_format.date = function(dt) {
        var year = dt.getFullYear();
        var month = dt.getMonth() + 1;
        var day = dt.getDate();
        return year + "年/" + month + "月/" + day + "日";
    };

    $.fn.dt_format.time = function(dt) {
        var hour = dt.getHours();
        var minute = dt.getMinutes();
        var second = dt.getSeconds();
        return hour + "时:" + minute + "分:" + second + "秒";
    };

    $.fn.dt_format.datetime = function(dt) {
        return $.fn.dt_format.date(dt) + " " + $.fn.dt_format.time(dt);        
    };
}(jQuery));
复制代码

点击HTML页面上的按钮, 分别转换出不同的时间格式并显示在页面上.

 

4. 插件的默认参数

上面的插件需要一个参数, 如果调用插件时没有带参数, 则导致js错误.

为了更好的用户体验, 下面给插件加入默认参数(也就是当前时间).

新的 plugin js如下:

复制代码
/* jquery plugin for test
 * filename: jquery-plugin.js
 */

(function ($) {

    $.fn.dt_format = function(options) {

        // 将用户的options 和 默认参数defaults 合并, 如有重复, 优先使用 options
        // 这里的 $.extend 的第一个参数是空的对象, 原因后面解释
        var settings = $.extend({}, $.fn.dt_format.defaults, options);
        
        this.each(function(){
            var elem = $(this);
            if (elem.hasClass("date"))
                elem.text($.fn.dt_format.date(settings.dt));
            if (elem.hasClass("time"))
                elem.text($.fn.dt_format.time(settings.dt));
            if (elem.hasClass("datetime"))
                elem.text($.fn.dt_format.datetime(settings.dt));
        });
        return this;
    };

    // 这里提供默认参数
    $.fn.dt_format.defaults = {
        dt: new Date(),
    };

    $.fn.dt_format.date = function(dt) {
        var year = dt.getFullYear();
        var month = dt.getMonth() + 1;
        var day = dt.getDate();
        return year + "年/" + month + "月/" + day + "日";
    };

    $.fn.dt_format.time = function(dt) {
        var hour = dt.getHours();
        var minute = dt.getMinutes();
        var second = dt.getSeconds();
        return hour + "时:" + minute + "分:" + second + "秒";
    };

    $.fn.dt_format.datetime = function(dt) {
        return $.fn.dt_format.date(dt) + " " + $.fn.dt_format.time(dt);        
    };
}(jQuery));
复制代码

 

HTML中调用插件时可以不用参数了

$(function(){
    $("#btn-plugin").click(function(){
        $("h2").dt_format(); // 这里可以不输入参数, 使用默认参数.
    });
});

 

补充: 合并参数时, 使用了 $.extend, 这个方法的作用是将所有参数 合并成一个大的json对象, 有相同的key时, 后面的参数覆盖前面的参数.

$.extend 的第一个参数是 {}, 之所以这样, 是因为合并后, 会破坏第一个参数, 所以不能将 defaults 放在第一个.

说明示例如下: (用chrome的console窗口可以看到输出结果)

复制代码
<!DOCTYPE HTML>
<html>
    <head>
        <title>jquery plugin test</title>
        <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
        <script type="text/javascript">
          $(function(){
              var defaults = { "id": 1, "name": "test"};
              var options = { "sex": "man", "name": "test2" };
              console.log("合并前, 各个参数如下:");
              console.log(defaults);
              console.log(options);
              console.log("合并后, 各个参数如下:");
              $.extend(defaults, options);
              console.log(defaults); // 这里可以发现 defaults中的内容是 defaults和options合并后的结果
              console.log(options);
          });

        </script>
    </head>
    <body>
    </body>
</html>
复制代码

 

5. 插件中的公有及私有函数

虽然 javascript 不是纯粹的面向对象的语言, 但是通过其强大的闭包功能, 也能构造出类似其他面向对象语言的公有/私有函数.

*功能型插件* 中的示例中3个函数 $.fn.dt_format.date, $.fn.dt_format.time, $.fn.dt_format.datetime 都是公有函数, 可以被插件使用者所覆盖.

比如, 将上面示例的HTML改为如下: (覆盖了插件中的 $.fn.dt_format.datetime 方法)

复制代码
<!DOCTYPE HTML>
<html>
    <head>
        <title>jquery plugin test</title>
        <script type="text/javascript" src="js/jquery-1.11.1.js"></script>
        <script type="text/javascript" src="js/jquery-plugin.js"></script>
        <script type="text/javascript">
          $(function(){
              $("#btn-plugin").click(function(){
                  $("h2").dt_format();
              });
          });

          $.fn.dt_format.datetime = function(dt) {
              alert("覆盖公有函数");
          };
        </script>
    </head>
    <body>
        <button id="btn-plugin">显示格式化的时间</button>
        <hr />
        <h1>当前时间:</h1>
        <h2 class="date">nothing</h2>
        <h2 class="time">nothing</h2>
        <h2 class="datetime">nothing</h2>
    </body>
</html>
复制代码

 

如果不想公开方法, 改变那3个函数定义方法即可:

复制代码
/* jquery plugin for test
 * filename: jquery-plugin.js
 */

(function ($) {

    $.fn.dt_format = function(options) {

        var settings = $.extend({}, $.fn.dt_format.defaults, options);
        
        this.each(function(){
            var elem = $(this);
            if (elem.hasClass("date"))
                elem.text(date(settings.dt));
            if (elem.hasClass("time"))
                elem.text(time(settings.dt));
            if (elem.hasClass("datetime"))
                elem.text(datetime(settings.dt));
        });
        return this;
    };

    $.fn.dt_format.defaults = {
        dt: new Date(),
    };

    var date = function(dt) {
        var year = dt.getFullYear();
        var month = dt.getMonth() + 1;
        var day = dt.getDate();
        return year + "年/" + month + "月/" + day + "日";
    };

    var time = function(dt) {
        var hour = dt.getHours();
        var minute = dt.getMinutes();
        var second = dt.getSeconds();
        return hour + "时:" + minute + "分:" + second + "秒";
    };

    var datetime = function(dt) {
        return date(dt) + " " + time(dt);        
    };
}(jQuery));
复制代码

这样, 插件使用者就不能覆盖 date, time, datetime 方法了.

 

6. 插件编写的注意点

是从 jQuery 官方网站的插件教程中总结出来的:

  1. 不要自定义语法
  2. 不要写死元素的id或者class, 将其以 options 的形式开放出来
  3. 提供 callback

转载于:https://www.cnblogs.com/hubl/p/5760300.html

jquery-plugin jquery-plugin:开发Jquery插件的简单示例, 立即下载

相关推荐

Visual Studio调试时遇到ntdll.dll的PDB文件缺失?别慌,这3个方法帮你搞定(附详细步骤)

本文详细解析了Visual Studio调试时ntdll.dll的PDB文件缺失问题,提供了3种实用解决方案:调整调试设置、配置符号服务器与缓存目录、手动下载管理符号文件。通过分步指导和高级技巧,帮助开发者快速恢复完整的调试功能,特别适用于Windows平台下的C++项目开发。

weixin_42537919的博客 520

引入plugins.js插件中引入 jQuery 时,浏览器报错 “$ is not a function ”

$(document).ready(function(){ // jQuery code is in here 此处的代码均使用了$ });报错:“$ is not a function ”plugins插件中引入 jQuery 时,您必须使用 jQuery,并且不使用 $(这是为了与其他库兼容)最终将使用$的地方,全部替换换为jQuery,解决了这个错误 jQuery(function(...

yangbaobao的博客 3679

如何将rvt(BIM)转换为点云格式

1、为什么将BIM转换为点云格式? 如何使设计BIM与真实场景进行配准,分析在建、未建、已建构建的情况,真实场景是通过点云生产的,和点云配准需要相同的格式。 2、如何转换? 实用工具revit,转换过程如下图,这样就可以转换成三角网格形式。 3、FBX还需要进行一次转换,即转换成点云常用的类型,如bin\ply\pcd等格式。 需要软件cloudcompare.exe,软件下载地址百度云 链接:https://pan.baidu.com/s/1pflcKNc04loBnS1yKR39hw 提取码:obaf

self_Name_的博客 4498

jQuery插件

(1)命名        通常情况下jquery插件采用下列模式命名    jquery.pluginName.js    min版本也有一个规范的命名:    添加一个min标识    jquery.pluginName.min.js(2)扩展jQuery的方式    1.使用jQuery.fn            ----推荐使用        在jQuery源码中jQuery.fn =jQ...

青色橙子 269

深度学习实战87-高中数学自适应测试系统研究与应用研发,前后台页面设计

大家好,我是微学AI ,今天给大家介绍一下深度学习实战87-高中数学自适应测试系统研究与应用研发,前后台页面设计。高中数学自适应测试系统旨在通过精准评估学生能力,用最少的题目发现其薄弱环节,并提供定制化的学习计划,帮助学生快速提升成绩。同时,系统结合了AI大模型实现自动判卷、生成报告,减轻教师负担,并支持个性化作业布置,使教学更加高效。学生可以清晰了解自身学习状态,教师也能获得精准的学生画像,实现差异化教学。

微学AI的博客 453

CANoe:入门介绍

CANoe网络通信分析:CANoe用户可以在台架上或者车辆中分析ECU和整个系统的多总线通信。Trace窗口:用于列出所有总线活动,例如消息或错误帧。对于每条消息,都可以显示单独的信号值Graphics窗口:用于在时间轴上以图形方式在线显示消息和诊断请求中传输的值,例如rpm或温度值Statistics窗口:用于显示有用的网络和节点统计信息,例如节点和帧级别的总线负载、突发计数器/持续时间、帧和错误的计数器/速率、控制器状态Data窗口:用于显示预选数据,例如数字或条形图数据。

jasonj333 9761

【jQuery】jQuery官方基本教程的学习笔记5-插件Plugins

一、How to create a basic plugin 1.创建基本插件 $.fn.greenify = function() { this.css( "color", "green" ); }; $( "a" ).greenify(); // Makes all the links green. 2.创建可链插件 $.fn.greenify = function() {

阿来小同学的博客 364

03 Token、Embedding、上下文窗口:开发者必须懂的三个基本概念

Token、Embedding 和上下文窗口是大模型应用开发的三个基础概念。本文从成本、速度、检索和上下文设计四个角度讲清它们的工程意义,帮助开发者理解为什么同一段内容会超限、变贵,为什么 RAG 能做语义检索。

老于的笔记的专栏 422

推荐使用:eslint-plugin-jquery,为您的现代JavaScript开发保驾护航!

推荐使用:eslint-plugin-jquery,为您的现代JavaScript开发保驾护航! 在前端开发的长河中,jQuery曾是一颗璀璨的明星,它简化了DOM操作,让开发者能够更加便捷地实现网页交互。然而,随着ECMAScript标准的不断进化和现代浏览器对原生API的支持日益完善,许多jQuery的功能已显得过时。正因如此,我们向您推荐一个旨在提升代码质量、鼓励使用原生JavaScript...

gitblog_00061的博客 375

手把手教你学Simulink——基于经典PID控制的电机系统场景实例:步进电机PID位置控制系统的实现

步进电机(Stepper Motor)是一种将电脉冲信号转化为角位移的执行元件,具有结构简单、控制方便、定位精度高等优点,广泛应用于数控机床、机器人、打印机、3D打印机等需要精确定位的场合。传统的步进电机多采用开环控制,但在高速或负载变化较大的情况下容易出现丢步、振荡等问题。为提高控制精度与响应性能,闭环PID控制被引入步进电机的位置控制中,通过编码器或旋转变压器等反馈装置,实现高精度、高稳定性的位置控制。本教程将带你使用构建一个基于PID控制的步进电机位置控制系统仿真模型步进电机建模。

MHD0815的博客 9703

【ComfyUI】Wan2.2 Animate 背景保留动作迁移视频生成

本文介绍了一个基于ComfyUI的高精度视频生成工作流"Wan2.2 Animate",该系统融合动作捕捉、图像拼接和LoRA加权等技术,能自动识别人脸并完成精准动作迁移,同时保持背景稳定。工作流采用模块化设计,包含输入提取、图像融合、模型加载等关键节点,核心模型Wan2.2-Animate-14B支持fp8精度与BlockSwap控制。流程分为图像输入、动作提取、多图合成等五个阶段,通过文本提示编码器和图像语义编码器实现语义驱动的动作生成,最终输出高质量视频,适用于虚拟形象驱动和

Mr数据杨 2322

jQuery Plugin 开发

1.Guideline:http://docs.jquery.com/Plugins/Authoring2.Example:http://www.learningjquery.com/2007/10/a-plugin-development-pattern3.重点:a)inside plugin function , "this" is jQuery Object, not DOM element...

weixin_30872733的博客 100

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

jquery 插件(plugin)开发

jQuery jQuery插件的开发包括两种: 一种是类级别的插件开发,即给jQuery添加新的全局函数,相当于给jQuery类本身添加方法。jQuery的全局函数就是属于jQuery命名空间的函数,另一种是对象级别的插件开发,即给jQuery对象添加方法。下面就两种函数的开发做详细的说明。 1、类级别的插件开发 类级别的插件开发最直接的理解就是给jQuery类添加类方法,可以理解为添加静

adenfeng的专栏 1403

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

jQuery插件开发: Watermark Plugin

最近在研究SunBlog和jQuery的整合, 不敢说有很多成就, 到此为止算是刚入门吧。jQuery最让我欣喜的是其插件式的开发模式, 这一点几乎和 DNN的模块概念同出一辙。我将陆续写些文章阐述DNN和jQuery, 比如如何开发插件(jQuery Plugin), 如何利用Ajax方式调用Webservice,如何优化UI等等。今天就简单说说如何开发jQuery插件,Goo...

weixin_30896763的博客 133

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

j​Q​u​e​r​y​ ​p​l​u​g​i​n​开​发

百度文档:http://wenku.baidu.com/link?url=RYzAhl-CMN9KHN3J9Takd5yb7zNNull4gJoFZRPA0YmJYK_oCpV2a7vW5FW6T38hPyObDYIH4HxVrKTb6SYSqgQ0Xpv3XmhxwyTeNNEh1ke

Jamkier's zone 2660

深入浅出JQuery (四) 如何自己开发 plugin 详解

简介 通俗的理解插件就是为了完成某一项功能而存在的,叫它插件可以理解为即插即用的一件东西,它的目的是给已经有的函数或者方法做一个封装,来完成特定功能。 比如最近很火的抢票插件等等,打个比方好比是初中数学中很多函数,如正函数、余弦函数等组合在一起,形成一个新的函数,完成一个更复杂的功能而开发出来的聚合函数。 种类 封装对象方法 将用JQuery选择器获取的对象的方法

李龙生 2851

jQuery插件开发[A Plugin Development Pattern 中文]

近期要准备一个web前端技术交流会的内容,所以陆续会有一些整理的资料发布,JQuery目前在组内日常开发中占据了重要地位,但各自为战的情况 很明显,要做到重用和通用,形成插件是不错的办法,特别是基于JQuery的插件,具有使用简单,可参数化配置等优点。这篇文章就介绍了如何开发 JQuery的插件。原文地址是:http://www.learningjquery.com/2007/10/a-pl...

Java开发与学习 248

jquery插件开发范例---A Plugin Development Pattern

原文地址:[url]http://www.learningjquery.com/2007/10/a-plugin-development-pattern[/url] [b]Claim only a single name in the jQuery namespace[/b] This implies a single-plugin script. If your script contain...

wangsong76的专栏 180

jQuery_Bootstrap

是前端开发中非常著名的开源框架

m0_71299382的博客 849

使用jQuery开发插件

jQuery开发插件的方法:jQuery.fn.extend();2、在HTML中引入jquery和JS文件并调用函数。1、创建JS文件plugin.js。

qq_39460057的博客 260

tableExport.jquery.plugin 常见问题解决方案

`tableExport.jquery.plugin` 是一个开源的 jQuery 插件,旨在帮助开发者将 HTML 表格导出为多种格式,包括 JSON、XML、CSV、TSV、TXT、SQL、Word、Excel、PNG 和 PDF。该项目托管在 GitHub 上,地址为 [https://github.com/hhurz/tableExport.jquery.plugin.git](https...

gitblog_07172的博客 651
上一篇: nodejs入门实例(一)
下一篇: yun2win-web端im快速接入方法
weixin_30700977
博客等级 码龄11年 104粉丝 1341原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值