jQuery.fn.log = function(message) {
  if (typeof(message) == 'object') {
    string = '{';
    $.each(message, function(key, value) {
      string += key + ': ' + value + ', ';
    });
    string += '}';
    message = string;
  }
  return this.each(function() {
    $context = $(this);
    while ($context.length) {

      $log = $context.find('.log');      if ($log.length) {
        $('<div class="log-message" />').text(message).appendTo($log).hide().fadeIn();        break;
      }
      $context = $context.parent();
    }
  });
};
尤其是加粗部分的含义,关键在于为什么要使用each和一系列的if判断运行效果如下图:

解决方案 »

  1.   

    点一下Click Here  下面就增加一条  Thanks for clicking the button!
      

  2.   


    jQuery.fn.log = function(message) {
      if (typeof(message) == 'object') {//判断类型是否为object
        string = '{';//这里应该是拼接字符串
        $.each(message, function(key, value) {//循环 循环message里面的对象
          string += key + ': ' + value + ', ';//比如一个按钮  key里面会有id class等  value就是相应的东西
        });
        string += '}';
        message = string;
      }
      return this.each(function() {
        $context = $(this);
       <strong> while ($context.length) {
         
          $log = $context.find('.log');
     
          if ($log.length) {
            $('<div class="log-message" />').text(message).appendTo($log).hide().fadeIn();//这里是添加的事件吧
     
            break;
          }
          $context = $context.parent();</strong>
        }
      });
    };也是新人
    不是很了解的部分就不说了~~  
      

  3.   

    感谢  ShenShiampMoYi 给我顶了
      

  4.   

    jQuery.fn.log = function(message) {
      if (typeof(message) == 'object') {//判断类型是否为object,通过button输出的信息可以是string也可以是json形式的.
        string = '{';//这里应该是拼接字符串
        $.each(message, function(key, value) {//循环 循环message里面的对象
          string += key + ': ' + value + ', ';//比如一个按钮  key里面会有id class等  value就是相应的东西
        });
        string += '}';
        message = string;
      }
      return this.each(function() {//这里的this指出发事件的地方,应该是button
        $context = $(this);
        while ($context.length) {
          $log = $context.find('.log');
          if ($log.length) {//查找该节点下是否有class为log的节点
            $('<div class="log-message" />').text(message).appendTo($log).hide().fadeIn();//这里是在之前的节点下面添加消息,并做出一种显示效果
            break;
          }
          $context = $context.parent();//得到this的父节点,循环查找
        }
      });
    };
      

  5.   

      return this.each(function() {//这里的this指出发事件的地方,应该是button
        $context = $(this);
        while ($context.length) {前面使用了each,后面为什么还要使用while 是为了什么效果,请大神们看一下
      

  6.   

    button只有一个为什么还要each 呢
      

  7.   


    这是一种通用的函数,不能因为你只有一个button就用each,这样当你有多个button就可以兼容使用.
    while循环是在对.log这个class的节点进行循环,查找父节点直到最上层.
      

  8.   

    8楼的解释是正确的。
    你给出的这段代码定义了一个叫做log的jquery方法,如果是单个的dom元素调用该方法(如$("#btn").log()),用不用each都是可以的。但是如果是很多按钮都需要调用该方法(即$(".btn").log())那么each就是必须的了,each的意义就在于使得每个元素都调用该方法,此时如果没有each那么只有$('.btn')中的第一个class=btn的元素会调用该方法。