Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
sofish opened this issue Apr 25, 2016 · 4 comments
Open

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

sofish opened this issue Apr 25, 2016 · 4 comments
Milestone

Comments

@sofish
Copy link
Owner

sofish commented Apr 25, 2016

现在,用 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();
@sofish sofish added this to the Daily Post milestone Apr 25, 2016
@ccirene
Copy link

ccirene commented Apr 26, 2016

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

@sofish
Copy link
Owner Author

sofish commented Apr 26, 2016

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

@ccirene
Copy link

ccirene commented Apr 26, 2016

对初学者要深入浅出

@marcccc
Copy link

marcccc commented Oct 28, 2016

大拇指~大拇指

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants