[英]How to figure out how many times a function has been uniquely called
我是 javascript 新手,并试图从头开始学习。 我有一个脚本,我可以在其中使用单选按钮、面积和周长进行两种不同的计算。 我想显示人们计算出不同计算的次数。 如果我用来显示按钮的点击次数,那么它会将所有内容都计算在内,但我该如何将它们分开?
document.getElementById("calculate").addEventListener("click", function() {
var button = document.getElementById("calculate");
var x, text;
x = document.getElementById("radius").value;
if (document.getElementById("area").checked) {
if (isNaN(x) || x < 1 || x > 100) {
text = "Fel radie";
document.getElementById('radius').value = '';
} else {
let radius = document.getElementById("radius").value;
area = Math.PI * radius * radius;
}
if (document.getElementById("areaoutput").innerHTML = text);
else(document.getElementById("areaoutput").innerHTML = "Area = " + area);
}
if (document.getElementById("circumference").checked) {
let radius = document.getElementById("radius").value;
if (isNaN(x) || x < 1 || x > 100) {
text = "Fel radie";
document.getElementById('radius').value = '';
} else {
let radius = document.getElementById("radius").value;
circumference = Math.PI * 2 * radius;
}
if (document.getElementById("circoutput").innerHTML = text);
else(document.getElementById("circoutput").innerHTML = "Circumference = " + circumference);
}
if (document.getElementById("area").checked) {
var count = localStorage.on_load_counter || 0;
var button = document.getElementById("calculate");
var display = document.getElementById("areacount");
button.onclick = function() {
localStorage.on_load_counter = display.innerHTML = ++count;
}
}
if (document.getElementById("circumference").checked) {
var count = localStorage.on_load_counter || 0;
var button = document.getElementById("calculate");
var display = document.getElementById("circcount");
}
button.onclick = function() {
localStorage.on_load_counter = display.innerHTML = ++count;
}
}, false);
尝试做这样的事情
var combinationsDone = [];
然后每次用户进行计算时,您都会向combinationsDone
添加一个对象。
例如,如果它们的半径为 5,并且未检查周长,则您应该这样做。
var combination = {
radius: 5,
circumference: false
}
if(!combinationsDone.includes(combination)){
combinationsDone.push(combination);
}
它的作用是确保在添加组合之前之前没有记录组合。 然后,当您想要获得他们完成的不同组合的数量时,只需使用combinationsDone.length
。
您可以使用全局变量。 每次调用该函数时都会增加。
var myFuncCalls = 0;
function myFunction()
{
myFuncCalls++;
alert( "I have been called " + myFuncCalls + " times" );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.