我目前正在学习 JavaScript,并且编写了这段代码(它运行良好),但我知道必须有一种方法可以更好地自动化它。我对循环有点模糊,但据我所知,我不知道在这种情况下可以使用一个:
function calculation() {
var num = document.getElementById("input").value;
var trCalc = num % 25;
var tipColorName = document.getElementById("tipColorName");
var ringColorName = document.getElementById("ringColorName");
var tipBlock = document.getElementById("tipBlock");
var ringBlock = document.getElementById("ringBlock");
// Pair Calculations
if (trCalc > 0 && trCalc <= 5) {
tipColorName.innerHTML = "White";
tipBlock.setAttribute("style", "background-color: #f2f2f2; color: #2f2f2f;");
}
if (trCalc > 5 && trCalc <= 10) {
tipColorName.innerHTML = "Red";
tipBlock.setAttribute("style", "background-color: #e24341; color: white;");
}
if (trCalc > 10 && trCalc <= 15) {
tipColorName.innerHTML = "Black";
tipBlock.setAttribute("style", "background-color: #2f2f2f; color: white;");
}
if (trCalc > 15 && trCalc <= 20) {
tipColorName.innerHTML = "Yellow";
tipBlock.setAttribute("style", "background-color: #f4ca37; color: #2f2f2f;");
}
if (trCalc > 20 && trCalc <= 24 || num % 25 == 0 && num > 0 ) {
tipColorName.innerHTML = "Violet";
tipBlock.setAttribute("style", "background-color: #844ae0; color: white;");
}
if ([1, 6, 11, 16, 21].includes(trCalc)) {
ringColorName.innerHTML = "Blue";
ringBlock.setAttribute("style", "background-color: #426ffe; color: white;");
}
if ([2, 7, 12, 17, 22].includes(trCalc)) {
ringColorName.innerHTML = "Orange";
ringBlock.setAttribute("style", "background-color: #f27f42; color: #2f2f2f;");
}
if ([3, 8, 13, 18, 23].includes(trCalc)) {
ringColorName.innerHTML = "Green";
ringBlock.setAttribute("style", "background-color: #25d366; color: white;");
}
if ([4, 9, 14, 19, 24].includes(trCalc)) {
ringColorName.innerHTML = "Brown";
ringBlock.setAttribute("style", "background-color: #917260; color: #2f2f2f;");
}
if ([5, 10, 15, 20 ].includes(trCalc) || num % 25 == 0 && num > 0 ) {
ringColorName.innerHTML = "Slate";
ringBlock.setAttribute("style", "background-color: grey; color: #2f2f2f;");
}
任何帮助表示赞赏!