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

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

最佳答案

您可以简单地向每个插件添加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/

09-19 16:27