这就是问题所在:有一个“文本”类型的输入:
<input id="WPVG" type="text" name="workpay">
输入小数(例如 1.1),但是当我尝试使用小数值在任何条件下应用结果值时,系统仅选择两个可能的选项:0 和 1,并忽略所有其他小数选项。没有任何错误,这让我无法找出问题所在。
let WorkPayVG = 0;
WorkPayVG = Number(document.querySelector('[name="workpay"]').value);
if (WorkPayVG == 0) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! Your people are unhappy that you don\'t pay them! Settle this issue quickly or it may lead to an uprising and loss of people!';
} else if (0 < WorkPayVG <= 0.25) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! Your people are unhappy that you pay them too little for their work! Please resolve this issue quickly or it may lead to people fleeing!'
} else if (0.25 < WorkPayVG <= 0.5) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! You pay your people too little! If you don\'t take action, they will begin to starve!';
} else if (0.5 < WorkPayVG <= 0.75) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! Your people\'s income is barely enough to make ends meet!';
} else if (0.75 < WorkPayVG <= 1) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'green';
document.getElementById('RVG03').innerHTML = 'Your people are fed and clothed, what else is needed for happiness?'
console.log('WorkPayVG 0.75-1:', WorkPayVG);
} else if (WorkPayVG > 1) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'green';
document.getElementById('RVG03').innerHTML = 'Your people are happy about your generosity, which translates into increased efficiency at work.';
console.log('WorkPayVG >1:', WorkPayVG);
}
帮助我了解出了什么问题?为什么系统看不到小数?我怀疑问题出在数据类型上,但我不明白如何告诉系统它需要考虑小数部分。
在 JavaScript 中,比较运算符不支持在同一表达式中使用两个运算符(< 和 <=)进行范围比较。相反,您应该单独比较每个值。
我建议完全放弃多个 if,创建一个具有边界值的数组并循环遍历它。这样既更清晰又更紧凑。