jQuery 输出到控制台 2 个变量的总和
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14920322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery output to console sum of 2 variables
提问by DigiKev
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
我现在希望能够增加价值clickBehaviour
和tabBehaviour
这个与每次点击一起输出到控制台或tab
I have attempted this, but with my limited JavaScript knowledge I keep returning NaN
我已经尝试过这个,但由于我有限的 JavaScript 知识,我一直在返回 NaN
回答by
You can simply add a getBehaviour()
method to each plugin like below:
您可以简单地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);
}
};
};
And print it using below code:
并使用以下代码打印它:
function printSum() {
console.log('Sum:' + (c.getBehaviour() + t.getBehaviour()));
}
printSum();
Here is jsfiddle. http://jsfiddle.net/FYAzw/
这是jsfiddle。http://jsfiddle.net/FYAzw/