jQuery输出到控制台的2个变量之和

时间:2013-02-17 10:55:06

标签: jquery jquery-plugins

以下代码跟踪用户遍历表单完成的点击次数或标签数量,并添加行为评分:

$(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

1 个答案:

答案 0 :(得分:8)

您只需向每个插件添加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/