开发者社区> 问答> 正文

jquery 插件开发 为什么 return this.each(function (){})

var jQuery = $;
console.dir(jQuery);
(function($) {    
  // 插件的定义    
  $.fn.hilight = function(options) {    
    debug(this);    
    // build main options before element iteration    
    var opts = $.extend({}, $.fn.hilight.defaults, options);

    console.dir(this);

    this.each(function (){
      console.log(arguments);
    });

    console.dir(this.each);
    // iterate and reformat each matched element 
    return this.each(function() {   

      console.dir(arguments);

      $this = $(this);    
      // build element specific options    
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;    
      // update element styles    
      $this.css({    
        backgroundColor: o.background,    
        color: o.foreground    
      });    
      var markup = $this.html();    
      // call our format function    
      markup = $.fn.hilight.format(markup);    
      $this.html(markup);    
    });    
  };    
  // 私有函数:debugging    
  function debug($obj) {    
    if (window.console && window.console.log)    
      window.console.log('hilight selection count: ' + $obj.size());    
  };    
  // 定义暴露format函数    
  $.fn.hilight.format = function(txt) {    
    return '<strong>' + txt + '</strong>';    
  };    
  // 插件的defaults    
  $.fn.hilight.defaults = {    
    foreground: 'red',    
    background: 'yellow'    
  };    
// 闭包结束    
})(jQuery); 

为什么要在 $.fn.hilight 中返回this.each();
直接返回this,不也完成了链式调用的需要

展开
收起
小旋风柴进 2016-03-26 09:51:55 3000 0
1 条回答
写回答
取消 提交回答
  • 在返回this之前,需要完成插件的功能hilight,
    因为调用的hilight插件的为一个jquery对象数组,所以需要调用each方法对每一个对象执行hilight

    当然你可以

    this.each(function(){
    ....
    });
    
    return this;
    2019-07-17 19:15:25
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
23-Vue.js在前端...1506518547.pdf 立即下载
Delivering Javascript to World 立即下载
JavaScript函数 立即下载