本文介绍了jQuery输出到控制台的2个变量的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码跟踪用户遍历表单完成的点击或制表符次数并添加行为得分:
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();
});
};
});
});
我现在希望能够将clickBehaviour
和tabBehaviour
的值加在一起,并通过单击或单击
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
我已经尝试过,但是由于我有限的JavaScript知识,我一直返回NaN
I have attempted this, but with my limited JavaScript knowledge I keep returning NaN
推荐答案
您可以简单地向每个插件添加getBehaviour()
方法,如下所示:
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();
这是jsfiddle. http://jsfiddle.net/FYAzw/
Here is jsfiddle. http://jsfiddle.net/FYAzw/
这篇关于jQuery输出到控制台的2个变量的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!