2013-02-17 33 views
2

下面的代碼追蹤有多少點擊或選項卡通過遍歷形式提供給用戶完成的總和,並增加了一個行爲學評分:jQuery的輸出到控制檯2個變量

$(function() { 
    $.fn.clickCount = function() { 
     var clickCount = 0; 
     var clickBehaviour = 0; 

     return { 
      increment: function() { 
       clickCount++; 
      }, 
      behaviour: function() { 
       clickBehaviour -= 5; 
      }, 
      print: function() { 
       console.log('Click count:' + clickCount); 
       console.log('Click behaviour:' + clickBehaviour); 
      } 
     }; 
    }; 

    $.fn.tabCount = function() { 
     var tabCount = 0; 
     var tabBehaviour = 0; 

     return { 
      increment: function() { 
       tabCount++; 
      }, 
      behaviour: function() { 
       tabBehaviour += 5; 
      }, 
      print: function() { 
       console.log('Tab count:' + tabCount); 
       console.log('Tab behaviour:' + tabBehaviour); 
      } 
     }; 
    }; 

    var $input = $('input, select, textarea'); 
    var c = $.fn.clickCount(); 
    var t = $.fn.tabCount(); 

    $input.mousedown(function() { 
     c.increment(); 
     c.behaviour(); 
     c.print(); 
    }); 

    $input.keydown(function(e) { 
     var keyCode = e.keyCode || e.which; 

     if (e.keyCode === 9) { 
      $(this).each(function() { 
       t.increment(); 
       t.behaviour(); 
       t.print(); 
      }); 
     }; 
    }); 
}); 

我現在希望能夠添加與每一次點擊或標籤控制檯的clickBehaviourtabBehaviour一起輸出該值

我嘗試這一點,但我有限的JavaScript知識,我的回頭率NaN

回答

7

您可以將getBehaviour()方法簡單地添加到每個插件象下面這樣:

$.fn.clickCount = function() { 
    var clickCount = 0; 
    var clickBehaviour = 0; 

    return { 
     increment: function() { 
      clickCount++; 
     }, 
     behaviour: function() { 
      clickBehaviour -= 5; 
     }, 
     getBehaviour: function(){ 
      return clickBehaviour; 
     } 
     print: function() { 
      console.log('Click count:' + clickCount); 
      console.log('Click behaviour:' + clickBehaviour); 
     } 
    }; 
}; 

而且使用下面的代碼打印:

function printSum() { 
    console.log('Sum:' + (c.getBehaviour() + t.getBehaviour())); 
} 
printSum(); 

這裏的jsfiddle。 http://jsfiddle.net/FYAzw/

+0

謝謝。這比我想象的要簡單得多。 – DigiKev 2013-02-17 14:21:59