jQuery output to console sum of 2 variables

我的未来我决定 提交于 2020-01-13 14:47:21

问题


The following code tracks how many clicks or tabs are completed by a user traversing a form and adds a behavioural score:

$(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();
            });
        };
    });
});

I now want to be able to add the value of clickBehaviour and tabBehaviour together and output this to the console with each click or tab

I have attempted this, but with my limited JavaScript knowledge I keep returning NaN


回答1:


You can simply add a getBehaviour() method to each plugin like below:

$.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);
        }
    };
};

And print it using below code:

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

Here is jsfiddle. http://jsfiddle.net/FYAzw/



来源:https://stackoverflow.com/questions/14920322/jquery-output-to-console-sum-of-2-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!