问题
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