sofish / learn-js

老婆想学 js 这件事就是一个政治任务
142 stars 9 forks source link

第十一天:写一个 jQuery 插件 #13

Open sofish opened 8 years ago

sofish commented 8 years ago

现在,用 jQuery 的公司还很多,但是拿出来说的已经很少了。还有 15 分钟就要去跑步,加上老婆还在整天跟 jQuery 打交道,写两句说明一下。拿官方的例子说明一下:

// 避免冲突,创建一个函数自执行函数,并把 `jQuery` 传入
(function( $ ) {

    // 用 `$.fn.插件名` 来定义一个新的插件
    // 关于插件为什么不用 `new`,`$.fn` 是什么意思,可以看:
    // http://stackoverflow.com/questions/4083351/what-does-jquery-fn-mean
  $.fn.showLinkLocation = function() {

    // `this` 即 `$()` 选中的集合
    // `filter` 筛选这个选中集合中的 `<a>`
    // 通常插件都会用 `each` 来循环整个集合,因为每个 `$()` 都会返回一个 jQuery 集合
    this.filter( 'a' ).each(function() {
      var link = $( this );
      link.append( ' (' + link.attr( 'href' ) + ')' );
    });

    // jQuery 其中一个最大的特点是链式调用,而 `return this` 返回一个 jQuery 对象让链式调用成为现实
    return this;

  };
}( jQuery ));

// 执行插件
$( 'a' ).showLinkLocation();
ccirene commented 8 years ago

你这是流水账,别人写的比你清楚多了http://www.cnblogs.com/Wayou/p/jquery_plugin_tutorial.html

sofish commented 8 years ago

@ccirene 写的长不一定就好,我几行注释他要写很多段,另外还没介绍 $·fn 的原理

ccirene commented 8 years ago

对初学者要深入浅出

marcccc commented 7 years ago

大拇指~大拇指